From c5fd96e935028b72182d58a611152bee6a8e533b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:30:19 +1300 Subject: [PATCH 01/11] Add durable authored-Draft coordination and authorization ordering --- .github/workflows/ci.yml | 109 +- ...urable-fenced-multi-owner-draft-commits.md | 2 +- .../account-service/api-contracts.md | 12 + .../game-design-service/api-contracts.md | 8 +- .../world-management-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 10 - ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 + .../world-runtime-and-movement.md | 2 + .../DraftAuthorizationFenceBinding.java | 338 ++++ .../DraftAuthorizationFenceRepository.java | 514 ++++++ ...V57__draft_commit_authorization_fences.sql | 167 ++ ...orizationFencePostgresIntegrationTest.java | 581 ++++++ .../DraftAuthorizationFenceBindingTest.java | 398 ++++ .../common/authoring/DraftCommitBinding.java | 454 +++++ .../draft/AuthoredDraftPublishSelection.java | 352 ++++ ...thoredDraftPublishSelectionRepository.java | 249 +++ .../DraftCommitCoordinatorRepository.java | 1611 +++++++++++++++++ ...V42__durable_draft_commit_coordination.sql | 865 +++++++++ .../V43__authored_draft_publish_selection.sql | 265 +++ ...ishSelectionRepositoryIntegrationTest.java | 600 ++++++ ...tCoordinatorRepositoryIntegrationTest.java | 877 +++++++++ .../AuthoredDraftPublishSelectionTest.java | 144 ++ .../draft/DraftCommitBindingTest.java | 224 +++ .../tenant/WorldAuthoredGraphSnapshot.java | 206 +++ .../WorldAuthoredGraphSnapshotCapture.java | 624 +++++++ .../WorldAuthoredGraphSnapshotRepository.java | 599 ++++++ .../WorldDesignPublicationFenceEvidence.java | 51 +- ...WorldDesignPublicationFenceRepository.java | 201 +- .../tenant/WorldDraftRegionCommitPlan.java | 234 +++ .../V28__world_authored_graph_snapshot.sql | 329 ++++ ...dGraphSnapshotPostgresIntegrationTest.java | 770 ++++++++ ...DesignPublicationFenceIntegrationTest.java | 434 ++++- .../WorldAuthoredGraphSnapshotTest.java | 136 ++ ...rldDesignPublicationFenceEvidenceTest.java | 79 +- .../WorldDraftRegionCommitPlanTest.java | 540 ++++++ 36 files changed, 11857 insertions(+), 134 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V57__draft_commit_authorization_fences.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/DraftCommitBindingTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d59e4563c..2f634ae11e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1342,7 +1342,9 @@ jobs: --strict \ --require-suite net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#rollbackAndCommittedExactReadbackRetainOneImmutableAttempt()' \ - --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameCanonicalTenantAndVersionRowCanBeLockedThroughDifferentIntakes()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed()' \ @@ -2065,6 +2067,111 @@ jobs: fi echo "::endgroup::" + - name: Capture Account authored-draft publication PostgreSQL XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-authored-draft-publication-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*DraftAuthorizationFencePostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Capture Game Design draft commit coordinator PostgreSQL XML + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-draft-commit-coordinator-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/game-design-service/build/test-results/integrationTest/TEST-*DraftCommitCoordinatorRepositoryIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Capture Game Design authored-draft publish selection PostgreSQL XML + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-authored-draft-publish-selection-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/game-design-service/build/test-results/integrationTest/TEST-*AuthoredDraftPublishSelectionRepositoryIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Capture World authored-graph snapshot PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-authored-graph-snapshot-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldAuthoredGraphSnapshotPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Capture World publication fence PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-publication-fence-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldDesignPublicationFenceIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Account authored-draft publication PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#changedCompleteBindingsConflictWithoutRewritingOriginal()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering()' \ + account-service + + - name: Verify Game Design authored-draft publication PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#exactClaimReplayRetainsFullBindingAndChangedRetryConflictsWithoutRewrite()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#pendingBindingAndOwnerRowsRollBackTogether()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#concurrentExactClaimsConvergeOnOneImmutableBinding()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#partialUnknownOwnerResultKeepsApplicationSlotAndCannotCreateVisibilityFence()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#exactAppliedResultReplayIsImmutableBeforeAndAfterSlotRelease()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#mixedFinalAbortPreservesPriorFenceAndOwnerEvidenceAndFencesDelayedAttempts()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#unknownOwnerAndMissingRowsCannotProduceFinalAbort()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#allAppliedOwnersIncludingGameDesignCanBeFinalAbortedWithoutVisibility()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#directSqlFinalAbortRejectsMissingRequiredOwnerRows()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#reusesExistingAuthoredVersionAndExactReplayIgnoresLaterServerState()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#rejectsPublishedScriptOnlyUnmappedPartialStaleAndMismatchedTargets()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#failedReservationTransactionLeavesNoSelection()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#versionRowLockSerializesSelectionAgainstApplicationSlotClaim()' \ + game-design-service + + - name: Verify World authored-draft publication PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest \ + --require-suite net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#exactSnapshotSurvivesRollbackAndConcurrentRetryWithFullGraphReadback()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#wrongTenantVersionParentEdgeDeniesCaptureBeforeSnapshotRetention()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#rollbackAndCommittedExactReadbackRetainOneImmutableAttempt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate()' \ + world-management-service + - name: Capture Account retained tenant-role PostgreSQL raw proof if: ${{ always() && matrix.module == 'account-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md b/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md index aedcf28232..82a0b4ca93 100644 --- a/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md +++ b/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The current implementation does not fully satisfy this decision. The held-back World mutation algorithm now advances its declared aggregate and scope epochs with expected-epoch storage predicates, including conflict-safe first claims; execution and remaining limitations are recorded in the [World tracker](../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). Some mutation shapes can still omit required scope fencing. `SaveRevision` can call World Management before Game Design persists its local revision, and there is no Game Design-owned durable commit/proposal coordinator with exact base and digest binding, complete affected-scope capture, per-owner apply status, or a creator-visible synchronized read fence. The registered World write remains denied without Account commit authorization. Existing revision ledgers and publish digests do not prove the complete contract. +The current implementation does not fully satisfy this decision. The held-back World mutation algorithm advances its declared aggregate and scope epochs with expected-epoch storage predicates, including conflict-safe first claims; execution and remaining limitations are recorded in the [World tracker](../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). Some mutation shapes can still omit required scope fencing. The new internal Game Design coordinator retains exact base/input binding, declared affected units, per-owner outcomes and a synchronized visibility record, but it is not connected to authenticated complete owner producers or normal authoring reads. `SaveRevision` can still call World Management before Game Design persists its local revision. The registered World write remains denied without Account commit authorization; internal coordination, authorization-order storage, revision ledgers and graph captures do not prove the complete contract. Current coordinator and publication-selection limits belong in the [Game Design tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), and Account producer/source-writer limits belong in [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Decision Record diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fcf737e97a..14ae134d79 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -44,6 +44,18 @@ Supported reads and downloads, including any controlled export the product suppo Decline or missing reacceptance does not itself cancel a subscription, delete content, decide a refund, or change billing or entitlement state. Subscription and billing consequences remain independent under [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) and the Account subscription lifecycle; payment or continued hosting never implies hosted-terms acceptance or marketplace enrollment. Future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +### Account-Owned Authored-Draft Authorization Fence + +Account owns the exact-operation authorization fence for the multi-owner Draft commit in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It binds the authenticated acting Account, canonical tenant and Version, stable operation and commit identities, complete mutation/input digest, expected Draft and base commit, and each applicable current role, party, terms and authority source with its independent version and checkpoint. Game Design and World remain the mutation owners. A capture, reservation, source receipt or finalization response is not reusable permission for a later owner commit. + +Account durably orders the exact operation against changes to every applicable authority source before either owner may commit. If the authority change wins, owner work must be rejected and the source mutation may finish only after definitive, exact no-commit/abort readback from both participants. If the operation wins, Account waits for every participant's definitive outcome. Both commits establish success; both definitive aborts or a definitive mixed vector establish terminal failure/nonpublication and may release the authorization fence without advancing synchronized Draft visibility. World's original applied result remains immutable even when Game Design definitively did not commit. An unknown Game Design result is not no-commit proof: recovery must first recover any valid committed result or obtain durable no-commit evidence that fences delayed attempts for the exact operation. Conflicting, missing or unavailable evidence remains pending. The operation ordering, all original participant results and source-change intent remain durable and immutable; they are not reopened or rewritten to manufacture matching outcomes. The prior synchronized version remains authoritative, and any compensation is a separate freshly authorized operation rather than a rewrite of original apply evidence. + +Each local transition uses a short owner transaction; no database lock spans a remote call and this is not a distributed database transaction. The source writer must participate in this ordering at its own commit, including issuer/account-wide changes when applicable. An Account-local reservation table alone does not prove that integration. The fence cannot extend authorization past a disclosed hosted-terms effective date or replace Account's required currentness check; the [hosted-terms contract](#account-owned-hosted-terms-and-creator-party) remains authoritative. Expiry, a lease, an operator acknowledgement, absence of an outcome, or a previously returned authorization result cannot bypass recovery or create permission. + +A disclosed terms effective date is never delayed by unresolved owner work and never grandfathers a later Game Design commit. Recovery may recognize an exact valid pre-deadline commit; otherwise Game Design must provide the durable final no-commit proof before the definitive mixed failure can settle. Staged or partially applied content remains non-authoritative and cannot satisfy publication or admission. + +**Implementation boundary:** the internal durable fence and participant readback storage are preparation, not an authenticated authorization producer or enabled writer. Complete source-writer participation, current role/party/terms proof, authenticated participant verification and both commit-versus-revocation interleavings remain required before canonical writes may be enabled. No public route or wire schema is selected by this section. Current proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + ### Account-Owned Playtest Grant Contract Account is the sole writer and read authority for non-public realm grants under [ADR 0138 (PLAYTEST-01)](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). The canonical grant identity is `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}`, with `playtestLifecycleId` immutable for the lifecycle; the record carries active/revoked state, monotonic `grantRevision`, `grantExpiresAt`, grantor/audit metadata, and the stable `requestId` outcome. `tenantAdmin` may create, extend, list, and revoke grants only within the exact tenant it administers. Authenticated `platformAdmin` may create, extend, revoke, or deliberately re-grant only through a distinct reasoned and audited `privileged_control`/break-glass grant-mutation branch governed by [Operator Authorization References](#operator-authorization-references) and [operator delegation](../../system-architecture-authz-route-matrix.md#operator-delegation). The branch requires an Account-issued authorization reference bound to the typed grant action, exact target and current playtest lifecycle, canonical `mutationDigest/v1` digest, live `platformAdmin` role, exact target-tenant generation, and `privileged_control` evidence. The grant's stable `requestId` remains the domain idempotency identity; the operator flow's `controlPlaneRequestId` is a separate correlation identity, and the reference binds both. The branch carries an explicit reason and audit attribution, is distinct from `tenantAdmin`, and is not tenant impersonation or a gameplay grant. Both paths validate the exact tenant, world, realm, account, and current playtest lifecycle; a slug or caller-supplied tenant identifier is not proof. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 9f7bb2a3c7..a2681c5f6c 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -143,12 +143,16 @@ The eventual creator-facing proto/OpenAPI shape must expose these semantics with Concrete RPC names, message fields, enums, pagination, and transport exposure remain deferred until the proto/OpenAPI contract is implemented. Whatever shape is selected must preserve the authority and visibility rules in ADR 0129. +The [Account-owned exact-operation authorization fence](../account-service/api-contracts.md#account-owned-authored-draft-authorization-fence) covers both World's owner commit and Game Design's final authoritative commit. Game Design preserves the original operation and complete binding during automatic recovery and supplies immutable, authenticated final commit or no-commit readback. It must not treat an Account capture or finalization result as permission for a later commit, or expose a partial World outcome as a synchronized Draft. Source changes remain subject to the Account-owned ordering until both participant outcomes are definitive; this producer/consumer integration is not established by the coordinator storage alone. + For every creator-intent `SaveRevision`, including revision-only requests, the exact Account party, acceptance-evidence, and material-acceptance-generation authorization must remain valid through Game Design's authoritative commit boundary. A preflight Account read alone is insufficient. If the authority is stale, mismatched, unavailable, or uncertain at that boundary, Game Design aborts the local transaction; no creator mutation or staged artifact becomes authoritative or externally reachable, and any staged artifact is cleanup/quarantine state, not success. The implementation must use commit-bound Account authorization/fence or equivalent validation without this contract selecting its mechanism. For a `SaveRevision` request carrying `worldDesignMutation`, the same authorization invariant applies to every participating authoritative mutation. Game Design carries the current Account authorization with the exact mutation descriptor to World, whose owner contract defines the [canonical Draft commit authorization boundary](../world-management-service/api-contracts.md#canonical-draft-commit-authorization). Until World can verify that authorization at its commit boundary, no participating owner commits and `SaveRevision` must not report success for a partial cross-owner commit; any staging remains non-authoritative. A source receipt, forwarded JWT, workload identity, or preflight-only check does not satisfy this producer obligation. ## Implementation Status +The current full-version reservation creates a new empty `Version` rather than selecting the existing authored Draft and its synchronized commit. Its public request does not carry that Draft/commit binding, and the World freeze and complete released-graph readback are not wired into this path. Consequently, existing revision rows, digest-read authentication, and release-bundle metadata do not prove that publication contains the edited world. The required durable commit and synchronized-visibility contract remains [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md); progress and remaining participant and Account authorization gates belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication-read APIs, and first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are present in the current proto/service path. Public full-version `PublishVersion` requires the Temporal `publish` orchestrator and returns `PUBLISH_WORKFLOW_UNAVAILABLE` when it is absent or disabled. The underlying command and readback callbacks remain workflow activities; they are not a synchronous public fallback. The four owner-to-owner digest reads use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding. End-to-end Temporal publication remains unproved: Automation rejects both unsupported digest scopes, Game Logic fails closed without the owner-local rule-input manifest/provenance, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). An exception after external export or release-bundle write leaves the original attempt outcome pending until reconciliation reads back its identity and all release evidence; a failure marker alone does not prove terminality or safe cleanup. `UploadPluginBundle` parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` row. Current intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; the current proto/storage also lack an append-only signature-evidence ledger and append RPC. `PublishPluginVersion` validates the uploaded bundle and published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and best-effort supersedes older published versions. The candidate now compares the dedicated `GAME_LOGIC` participant `abilitySchemaDigest` retained with its exact full-version release scope, commit and supported digest schema; an aggregate digest, absent value or wrong owner is rejected without publication mutation. The normal Game Logic ability-schema source producer and complete activation compatibility remain unproved. `RevokePluginVersion` and `ListPluginVersionStatusEvents` provide the current design-time revoke and append-only publication-event read surfaces; dedicated ability-schema proof and broader activation-time alias/binding validation remain open. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. @@ -187,7 +191,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e ## gRPC APIs - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. +- `PublishVersion` – target publication freezes the exact existing authored Draft and synchronized commit. The current Temporal path instead reserves a new empty Version, as recorded above. Exact workload authorization for participant digest reads is implemented; this is not Account creator/terms authorization through the owner commit, nor complete content publication proof. - `PublishScriptPatchVersion` – requests script-only publication for a base-version/patch identity. The current composed path fails at the Automation participant digest gate before notification; see Implementation Status and [Version Control](version-control.md#script-patch-versions-and-runtime-behavior) for the exact failure and the conditional later client-preflight seam. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. @@ -238,7 +242,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes a frozen version. Callers must provide a stable `publish_request_id`. The service derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. If the Temporal orchestrator is absent or disabled, the public operation fails closed with `PUBLISH_WORKFLOW_UNAVAILABLE`; the local publish command is used as a workflow activity, not as a synchronous fallback. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed, but the current Temporal path is still not proved end to end because content-scope and live mounted-certificate/activity evidence remain incomplete. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – target publication of the exact frozen authored Draft; the current request/reservation does not yet select that Draft or synchronized commit. Callers must provide a stable `publish_request_id`. The service derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. If the Temporal orchestrator is absent or disabled, the public operation fails closed with `PUBLISH_WORKFLOW_UNAVAILABLE`; the local publish command is used as a workflow activity, not as a synchronous fallback. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed; Account commit-bound creator/terms authorization, complete authored content, and live mounted-certificate/activity proof remain distinct outstanding gates. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 9ccf337872..de83f5a111 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -79,6 +79,8 @@ For a canonical Draft write, Account supplies the current tenant-scoped designer World verifies both the authenticated Game Design producer and the Account authorization against the exact descriptor at the owner commit boundary. A source receipt, source-qualified Draft/version read, forwarded JWT, workload identity, copied role/terms state, or preflight-only check cannot authorize the mutation or replace commit-time currentness verification. The path remains automatic through Account, Game Design, and World; it has no manual authorization or migration step. Missing, stale, mismatched, unavailable, or uncertain authorization denies or aborts the owner commit, and Game Design must not report a successful cross-owner commit. Any staged data remains non-authoritative cleanup/quarantine state. Canonical World writes remain denied until this commit-time verification is implemented and proved. +For multi-owner Draft commits, World participates in the [Account-owned exact-operation authorization fence](../account-service/api-contracts.md#account-owned-authored-draft-authorization-fence). Its immutable, authenticated commit or no-commit readback must bind the exact mutation and authorization operation; a successful Account preflight or finalization response cannot authorize a delayed World commit. World completion alone cannot release Account's fence while Game Design's final authoritative outcome is unresolved. These obligations do not enable the currently denied write path. + ### Publication freeze and terminal handoff (target state) The publication-freeze operations remain unavailable target contract surfaces. The internal owner-lock persistence prerequisite is not an authenticated freeze producer or terminal handoff; the [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records its current code and proof limits. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fdf58e82f0..6c0c2b671a 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -422,16 +422,6 @@ Entry format: - Outcome: Document rejected the unavailable-run conclusion and resumed the same sole watcher with the literal run URL and a separate workflow ID. The corrected watcher verified the assigned workflow/head and returned raw XML proving the required Account cases executed cleanly; the overall run completed with failures outside the Account job. No second watcher or duplicate parent polling was started. - Expected pattern: require the executed request identity to match the assignment before classifying an external failure. Distinguish a workflow ID from a run ID and retain any mismatched query as a delegation error, not provider evidence. -- `2026-10-05`: Enable a diagnostic report when the exact SpotBugs task hides its findings - - Context: Game Design's integration analyzer exited with code 3 without a report; repeating the exact task with `--info` still showed only the invocation and missing annotation class, not the finding. A temporary Gradle init script enabling an XML report on that same task exposed a nullable PostgreSQL read in the new composition test. - - Outcome: the missing-row read now fails explicitly, and the canonical composed check passes without suppressions or reduced analyzer coverage. The report-only script was a temporary diagnostic input, not repository tooling or substitute validation. - - Expected pattern: if the detailed log remains inconclusive, enable the affected task's report without changing its analysis or failure policy; fix the reported issue and rerun the normal gate. A missing annotation warning alone does not explain an analyzer failure. - -- `2026-10-05`: A successful diagnostic invocation may have skipped its analyzer - - Context: a focused Game Design SpotBugs diagnostic returned `BUILD SUCCESSFUL` without `-PfullCheck`; the task log showed `spotbugsMain SKIPPED`. Document briefly reported that as an isolated analyzer pass before checking the task state. - - Outcome: the skipped result was withdrawn, the exact task rerun with `-PfullCheck`, and its XML exposed the constructor finding behind the consolidated failure. No skipped diagnostic result was used as publication or completion proof. - - Expected pattern: preserve required check flags in diagnostic commands and inspect the actual task outcome, not just the process exit status, before attributing analyzer execution or calling a failure intermittent. - - `2026-10-05`: Cross-service test dependencies can leak another owner's Flyway migrations - Context: the new Game Design-to-World composition fixture added a World service test dependency. Its service JAR also supplied `db/migration`, so existing Game Design classpath-based Flyway fixtures failed on duplicate V1 migrations in CI; Docker-free local checks had skipped that setup. All eight new database cases passed, but six other required cases did not execute. - Outcome: selecting the World dependency's standard classes-only variant preserves its implementation and transitive dependencies without its migration resources. A resolved runtime-classpath diagnostic and full affected checks pass; exact corrected-state PostgreSQL execution is still required. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 422175ee04..ad76cf5aea 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The authored-publication candidate adds an internal durable Draft coordinator and existing-Draft publication selection. One shared complete-input codec retains the canonical target, exact base, ordered full revisions and complete declared owner/aggregate/scope epochs; immutable per-owner results and the synchronized visibility record retain exact binding and result bytes. V42 stores coordination, an application slot and immutable definitive final-abort evidence; a complete terminal mixed vector becomes failed nonpublication without advancing the prior synchronized view or rewriting owner outcomes. V43 reserves the caller-selected synchronized commit of an existing full Draft Version instead of allocating an empty publication Version. These are unwired storage components, not authenticated owner producers, normal editor visibility, a complete publication workflow or release proof. The current public full-version publish implementation still creates a new empty Version and does not consume this selection. The consolidated Core/Account/Game Design/World checks, schema generation, three boot JARs, formatting, analyzers, links and Markdown pass with 1,931 clean recorded unit executions and one MinIO skip; the final 12-second gate executes 12 tasks and reuses 142. All 545 PostgreSQL nodes, including nine coordinator and four selection methods, compile and skip locally without Docker. CI retains raw XML and strictly requires the named methods without skips; their runner execution remains open. Account commit-time authorization, typed owner completeness, partial-application recovery, participant evidence and release/terminal handoff remain required before the new normal path is enabled. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) owns that contract. + The World complete-binding prerequisite includes an explicitly unwired source-qualified current-Version consumer and component proof. Game Design returns its already-persisted canonical Version UUID and complete immutable Version/source provenance from the same read-only snapshot; World reads back the original local pair/source before comparing the exact source, UUID, state and descriptor epoch, preserves the original result on currentness denial, and performs no lifecycle mutation. Exact `e20471d6addc25ebe1e4b3afbc4ac648e116f5de` [CI37254215948](https://github.com/benhook1013/FireMUD/actions/runs/37254215948) has independently verified raw XML for all 29 required PostgreSQL methods: six Game Design complete-binding, eight World pair/currentness, four Game Design owner-snapshot, five version/mTLS (including two identity-composition), and six World identity methods. All 29 executed without skips, failures or errors. The nine existing Game Design owner suites also executed all 63 methods cleanly. The source-built merge `41895db449bef1cd13c98cc178fe80d70caadb35` has the expected `a339` and `e204` parents and the same tree; its raw XML was independently verified. This corrects the earlier `2ceefac830e6747bd088e075d992457f678adde9` checkpoint, where six Game Design complete-binding methods were skipped after World migrations leaked into existing Game Design fixtures. The classes-only dependency repair is now proved, with no pending runtime revalidation for that repair. Earlier local full Game Design/World checks and both boot JARs passed with 709 clean unit executions, one object-store unit skip and all 148 PostgreSQL nodes skipped without Docker. The [World tracker](./world-runtime-and-movement.md#current-status) owns World identity implementation and proof limits. This does not close normal Game Logic publication, canonical World content, commit-time owner/Account fencing or launch activation. The authored-source delivery batch adds V41 durable delivery intent in the same transaction as fresh `NEW_GAME_ROW` source registration, followed by authenticated World intake and independent receipt readback outside the Game Design transaction. A short Game Design owner transaction retains the first complete World receipt and independently reads it back; an exact completed retry returns that immutable acknowledgement before contacting World, while an ambiguous/lost acknowledgement retains the same intake identity for exact retry. Historical source-only retries are not backfilled, and retained sources do not receive a delivery intent. Full Game Design/World checks and both boot JARs pass with 718 clean unit executions, including all nine new delivery cases; one object-store unit case and all 158 PostgreSQL methods skip locally without Docker. At exact `db03a6d2d4a4c09a45540fcad183bb4469557415`, [CI37257109313](https://github.com/benhook1013/FireMUD/actions/runs/37257109313) executes all ten new methods without skips, failures or errors: seven PostgreSQL component cases mock outbound World calls, while three composition cases use actual Game Design and World PostgreSQL owners and physical workload mTLS with synthetic persisted creation fixtures. All 29 earlier required launch/identity/version methods and 63 existing Game Design owner methods also execute cleanly. Independent raw-XML parsing/hashing and expected merge parents with an equal source tree establish exact attribution. Forward V41 generation, migration numbering, workflow validation and 230 architecture-contract tests pass. The delivery path is not registered as a worker and does not enable a public creator, Account designer/terms authorization, content materialization, lifecycle preparation or activation. The [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#durable-fresh-source-delivery-to-world) owns delivery semantics; the [World tracker](./world-runtime-and-movement.md#current-status) records only its local consequence. Assigned proof is settled, but aggregate CI was still active with an unrelated, not-yet-diagnosed Python failure at observer handoff; no aggregate-green claim follows. 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 c827b82302..981d6e463f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. CI retains raw XML and requires every named fence case to execute without skips; corrected-state database execution remains open. This is not an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. + Exact corrected Account head `3440d4d646414c2c7244e5e0cc1b650cd9e242d8` has executed [CI37290103027](https://github.com/benhook1013/FireMUD/actions/runs/37290103027) proof. Account job `111698347142` succeeded; the strict log records all fourteen `AccountAuthenticationUuidIntegrationTest` cases passing without skips, including one execution of the repaired email-OTP method. No separate OTP XML artifact was uploaded, so that method's attribution rests on the strict job log. All twenty required role/journal/fresh-JOIN/physical-mTLS methods also passed: independently parsed raw suites record JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. The actual Game Session client PostgreSQL/mTLS suite passed 3/3 without skips before its later full check was cancelled; Game Session job `111698347041` and aggregate CI therefore did not pass. The cancellation log supplies no causal explanation. Verified checkout merge `c82c0262d55106fcbea0ed2329adfb1ff19098f1` has the exact World `f968b46adf12570e870b17e17fe0d4382e7078b4` and Account source parents and the same source tree `d39693e551631ed21fb1a6751eb4c4c6658a0e8c`. This closes the OTP fixture execution gap and repeats the physical component proof on that composed tree; upstream caller/policy, current-parent alignment, complete authorization, fresh images, live readiness and activation remain independent gates. At exact `b5cf5ae01bf546657c7601919ba704b99a56d939`, [CI37284046862](https://github.com/benhook1013/FireMUD/actions/runs/37284046862) completed with aggregate failure, Account job `111678940179` failure and Game Session job `111678940188` cancellation of unestablished cause. Nevertheless, independently parsed raw XML proves all twenty required Account cases passed without skips: eleven retained-role, two journal, five fresh-JOIN and two new physical mTLS cases. The actual Game Session client PostgreSQL/mTLS suite passed all three cases without skips, including fresh positive readback, exact retry, authenticated request echoes, wrong/unknown identity rejection and no source mutation. Full Account raw suites pass JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. Checkout logs and verified merge `1db0f4d5075cd980b90dc64c90a61daec2586ab5` establish exact World `0bb5da90df09a82e2456811066cb6320b3380ee9` and Account source parents; merge tree `d432827ecf4edd022ca6e50f8f0071f02ba87c0b` matches the source tree. This closes these physical producer/consumer component execution gaps, not authenticated upstream JOIN, realm/catalog admission, current-parent composition, registry authorization or activation. Root rehashed JOIN `05d7ec0f8b4365088530c0683d506c19eacd6da1d182bac1626b366285cce13c`, journal `379240db16df126fb1173de3c789a8cbcf58e33a2f67a19940c649a2b56b96d2`, reconciliation `2601fe70801883c9b8286e30a603aeabefc52681826f9b31ab782db615b7db50`, scope `044f2a210cdf770adcc77bf2076fd69164429b4537ab1f7a014b20150cdbc3cd` and Game Session PostgreSQL/mTLS `cfe8163275c615aac7de40a1cfcc577fed1f8224e05d4c381d0b1f4865d629c7`. 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 3eeb8b5a4b..bff6df0d0c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains complete immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the revision ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical exact readback does not create another capture after terminal state. The typed ordered REGION plan independently derives both required fence tuples and rejects unsupported or mismatched input; it neither writes content nor authenticates its supplied source binding. The combined four-module check passes, with 242 clean World unit results and all 61 World PostgreSQL nodes compiled but skipped locally without Docker. Graph component fixtures explicitly stipulate six-family and ledger rows in a test-only transaction-local seed scope, restore and assert normal triggers before digest/freeze/capture, and include unchanged V24 canonical-key write-denial proof. They do not prove a canonical content producer; their four graph and eight freeze cases still require runner execution. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. The canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and a numeric alias are not substitutes. + The held-back World mutation algorithm now uses full-tuple, expected-epoch SQL predicates for its declared aggregate and scope advances. An absent epoch can be claimed only from zero with a conflict-safe insert; stale, negative or overflowing expected counters cannot succeed. A losing advance raises `DRAFT_WRITE_CONFLICT` inside the existing owner transaction rather than committing content under an unconditional epoch save. The focused mutation suite executed 29 cases successfully. The consolidated World check, boot JAR, formatting, static analysis, links and Markdown passed with 227 unit executions and no unit skips; all 55 PostgreSQL integration methods, including five new deterministic race, tuple-isolation and rollback cases, compiled but skipped locally without Docker. The subsequent exact-source CI execution is recorded below. This closes a local storage primitive, not complete affected-scope validation, immutable complete-input retry binding, source-qualified content materialization, synchronized Draft visibility, Account authorization, publication or lifecycle. The registered mutation remains denied. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) remains the target contract. At exact source `f968b46adf12570e870b17e17fe0d4382e7078b4`, [CI37289016289](https://github.com/benhook1013/FireMUD/actions/runs/37289016289) World job `111694868974` succeeded. Root independently parsed and rehashed raw XML: all five new epoch-CAS methods executed once, passed and had zero skips, failures or errors. These prove real PostgreSQL first-claim and existing-row races, tuple isolation, rollback after a late scope conflict and rollback of authored content, both counters and ledger after an otherwise successful owner mutation. XML SHA-256 is `d779fe0a7214cba7901370cd59d0478113ed33721ca38d32d31af827bcc28eb6`. Job checkout and independently verified merge `467ca7355ef92583a74893b624bf740ca7b48205` bind exact base `071b35375b7b4c174147ed201c10dc50658b19a4` and source parents, with tree `96f74c67841d2f52a2673136308539eb6f50a667` identical to the source. The later World Gradle check also passed. Metadata-only runs `37289154141` and `37289180583` skipped build jobs and supply no execution credit. The aggregate was still active at observer closeout; complete authorization, synchronized publication, materialization, fresh-image/live and activation proof remain open. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java new file mode 100644 index 0000000000..27a201b2bd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java @@ -0,0 +1,338 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Exact immutable source material, not an authorization decision or authenticated actor proof. */ +public record DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + + public DraftAuthorizationFenceBinding { + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + requireUuid(id); + } + text(baseCommitId); + if (baseCommitId.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException("Base commit exceeds 256 UTF-8 bytes"); + } + decimal(expectedDraftEpoch, true); + gameDesignBinding = bytes(gameDesignBinding); + normalizedInput = bytes(normalizedInput); + DraftCommitBinding completeBinding; + try { + completeBinding = + DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException( + "Complete canonical Game Design binding required", corrupt); + } + if (!Arrays.equals(gameDesignBinding, completeBinding.canonicalBytes()) + || !requestId.equals(completeBinding.requestId()) + || !commitId.equals(completeBinding.commitId()) + || !tenantId.equals(completeBinding.target().canonicalTenantId()) + || !versionId.equals(completeBinding.target().canonicalVersionId()) + || !baseCommitId.equals(completeBinding.baseCommitId())) { + throw new IllegalArgumentException("Account fence differs from complete Game Design binding"); + } + if (!Arrays.equals(normalizedInput, gameDesignBinding) + || !completeBinding.digest().equals(inputDigest)) { + throw new IllegalArgumentException( + "Draft input must be the exact complete canonical binding"); + } + sources = List.copyOf(Objects.requireNonNull(sources)); + if (sources.isEmpty()) { + throw new IllegalArgumentException("Applicable Account sources are required"); + } + sources = sources.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Duplicate Account source scope"); + } + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] gameDesignBinding() { + return gameDesignBinding.clone(); + } + + @Override + public byte[] normalizedInput() { + return normalizedInput.clone(); + } + + /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, SCHEMA); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + frame(output, id.toString()); + } + frame(output, baseCommitId); + frame(output, "DRAFT"); + frame(output, expectedDraftEpoch); + frame(output, gameDesignBinding); + frame(output, normalizedInput); + frame(output, inputDigest); + frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(output, source.canonicalBytes()); + } + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + return output.toByteArray(); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 512) { + throw new IllegalArgumentException("Source participation key exceeds 512 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + } + + public enum Owner { + GAME_DESIGN, + WORLD + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + /** Only a future authenticated owner verifier may supply this exact durable readback. */ + public record OwnerReadback( + Owner owner, + Outcome outcome, + UUID operationId, + UUID commitId, + UUID fenceId, + String inputDigest, + byte[] fullBinding, + byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(operationId); + requireUuid(commitId); + requireUuid(fenceId); + if (inputDigest == null || !inputDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical digest required"); + } + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(DraftAuthorizationFenceBinding binding) { + if (!operationId.equals(binding.operationId()) + || !commitId.equals(binding.commitId()) + || !fenceId.equals(binding.fenceId()) + || !inputDigest.equals(binding.inputDigest()) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + } + + static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + static void canonicalUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + } + + static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } + } + + static void decimal(String value, boolean zero) { + if (value == null || !value.matches(zero ? "0|[1-9][0-9]*" : "[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical decimal string required"); + } + } + + static void frame(ByteArrayOutputStream output, String value) { + text(value); + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java new file mode 100644 index 0000000000..d72e58b5f0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -0,0 +1,514 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired durable ordering component. Every method requires a writable caller READ_COMMITTED + * Account transaction. Callers lock/revalidate actual authority sources first, then this component + * locks sorted source participation rows and sorted operations. Never hold these locks across RPC. + * Reservation and returned source evidence alone grant no owner commit permission. + * + *

Future authenticated capture/source-change and owner-readback producers are mandatory. This + * class does not authenticate supplied evidence or manufacture missing role/terms source state. + */ +public final class DraftAuthorizationFenceRepository { + private static final String FENCES = "account_draft_authorization_fences"; + private static final String SOURCES = "account_draft_authorization_sources"; + private static final String READBACKS = "account_draft_authorization_owner_readbacks"; + private static final String CHANGES = "account_draft_authorization_source_changes"; + private static final String CHANGED = "account_draft_authorization_changed_scopes"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected DSLContext is an internal owner-transaction persistence collaborator.") + public DraftAuthorizationFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum Ordering { + RESERVED, + COMMIT_ORDER, + REVOKE_ORDER + } + + public enum Settlement { + PENDING, + COMMITTED, + FAILED_NONPUBLICATION + } + + public record FenceSnapshot( + Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { + public FenceSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + public record OwnerResultSnapshot(Outcome outcome, byte[] readback, OffsetDateTime recordedAt) { + public OwnerResultSnapshot { + readback = readback.clone(); + } + + @Override + public byte[] readback() { + return readback.clone(); + } + } + + public record SourceChangeSnapshot( + UUID changeId, + byte[] binding, + String status, + OffsetDateTime requestedAt, + OffsetDateTime committedAt) { + public SourceChangeSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + /** Full exact mutation intent and independently captured affected source vector. */ + public record SourceChange(UUID changeId, List sources, byte[] mutation) { + public SourceChange { + DraftAuthorizationFenceBinding.requireUuid(changeId); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct affected sources required"); + } + mutation = DraftAuthorizationFenceBinding.bytes(mutation); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] mutation() { + return mutation.clone(); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-draft-source-change/v1"); + DraftAuthorizationFenceBinding.frame(out, changeId.toString()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + DraftAuthorizationFenceBinding.frame(out, mutation); + return out.toByteArray(); + } + } + + /** + * Already-existing source capture only. Future producer must establish completeness/currentness. + */ + public FenceSnapshot reserve(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record existing = readOperation(binding.operationId()); + if (existing != null) { + return snapshot(requireExact(existing, binding)); + } + if (hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + dsl.execute( + "INSERT INTO " + + FENCES + + " (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Irrevocable exact operation order; revalidate actual source state under its locks before + * calling. + */ + public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = requireExact(readOperation(binding.operationId()), binding); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.COMMIT_ORDER) { + return snapshot(row); + } + if (ordering == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Revocation precedes this owner commit"); + } + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + binding.operationId()); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Commit this WAITING result even when false: rolling back would lose revocation intent. True + * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. + */ + public boolean requestSourceChange(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record prior = readChange(change.changeId()); + if (prior != null) { + requireChange(prior, change); + if ("SOURCE_COMMITTED".equals(prior.get("status", String.class))) { + return true; + } + } else { + dsl.execute( + "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence source : change.sources()) { + dsl.execute( + "INSERT INTO " + CHANGED + " (change_id, source_key) VALUES (?, ?)", + change.changeId(), + source.key()); + } + } + for (UUID operation : affectedOperations(change.sources())) { + Record row = readOperation(operation); + if ("RESERVED".equals(row.get("ordering", String.class))) { + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'REVOKE_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + operation); + } + } + return allAffectedSettled(change.sources()); + } + + /** Verify before the first source mutation and retain the transaction through source commit. */ + public boolean sourceMutationPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + + /** + * Same transaction as actual source mutation/event/readback. No RPC or fake source write here. + */ + public void markSourceCommitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + if ("SOURCE_COMMITTED".equals(row.get("status", String.class))) { + return; + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ? AND status = 'WAITING'", + change.changeId()); + } + + /** Exact durable owner readback, supplied only by the future authenticated owner verifier. */ + public void recordOwnerReadback(DraftAuthorizationFenceBinding binding, OwnerReadback readback) { + requireTransaction(); + readback.requireBinding(binding); + Record row = requireExact(readOperation(binding.operationId()), binding); + if ("RESERVED".equals(row.get("ordering", String.class))) { + throw new IllegalStateException("Reservation alone cannot produce terminal owner evidence"); + } + Record prior = + dsl.fetchOne( + "SELECT readback FROM " + READBACKS + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + readback.owner().name()); + if (prior != null) { + if (!Arrays.equals(prior.get("readback", byte[].class), readback.canonicalBytes())) { + throw new IllegalArgumentException("Changed owner terminal evidence"); + } + return; + } + dsl.execute( + "INSERT INTO " + + READBACKS + + " (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + readback.owner().name(), + readback.outcome().name(), + readback.canonicalBytes()); + } + + public FenceSnapshot read(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Derived exact settlement only; original ordering and owner readbacks remain immutable. */ + public Settlement readSettlement(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + Record row = requireExact(readOperation(binding.operationId()), binding); + return settlement(binding.operationId(), Ordering.valueOf(row.get("ordering", String.class))); + } + + /** Absence means UNKNOWN, never no-commit proof. */ + public Optional readOwnerResult( + DraftAuthorizationFenceBinding binding, Owner owner) { + requireTransaction(); + requireExact(readOperation(binding.operationId()), binding); + Record row = + dsl.fetchOne( + "SELECT outcome, readback, recorded_at FROM " + + READBACKS + + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + owner.name()); + return row == null + ? Optional.empty() + : Optional.of( + new OwnerResultSnapshot( + Outcome.valueOf(row.get("outcome", String.class)), + row.get("readback", byte[].class), + row.get("recorded_at", OffsetDateTime.class))); + } + + /** Durable recovery discovery only; no auto-running worker or authority decision. */ + public List waitingSourceChanges() { + requireTransaction(); + return dsl + .fetch("SELECT * FROM " + CHANGES + " WHERE status = 'WAITING' ORDER BY change_id") + .stream() + .map( + row -> + new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class))) + .toList(); + } + + public SourceChangeSnapshot readSourceChange(SourceChange change) { + requireTransaction(); + Record row = readChange(change.changeId()); + requireChange(row, change); + return new SourceChangeSnapshot( + change.changeId(), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class)); + } + + private void lockSources(List sources) { + for (SourceEvidence source : sources) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + source.key()); + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.key()); + } + } + + private boolean hasWaitingChange(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT c.change_id FROM " + + CHANGES + + " c JOIN " + + CHANGED + + " s ON s.change_id = c.change_id WHERE s.source_key = ? AND c.status = 'WAITING'", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private List affectedOperations(List sources) { + return sources.stream() + .flatMap( + source -> + dsl + .fetch( + "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", + source.key()) + .getValues("operation_id", UUID.class) + .stream()) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList(); + } + + /** + * Commit order settles only after both exact definitive outcomes, including mixed failure. Revoke + * order requires both definitive aborts. Missing evidence always remains pending. + */ + private boolean allAffectedSettled(List sources) { + for (UUID operation : affectedOperations(sources)) { + Record row = readOperation(operation); + if (settlement(operation, Ordering.valueOf(row.get("ordering", String.class))) + == Settlement.PENDING) { + return false; + } + } + return true; + } + + private Settlement settlement(UUID operation, Ordering ordering) { + if (ordering == Ordering.RESERVED) { + return Settlement.PENDING; + } + List outcomes = + dsl + .fetch("SELECT outcome FROM " + READBACKS + " WHERE operation_id = ?", operation) + .getValues("outcome", String.class) + .stream() + .map(Outcome::valueOf) + .toList(); + // The owner CHECK and (operation_id, owner) primary key admit exactly these two owners. + if (outcomes.size() != 2) { + return Settlement.PENDING; + } + boolean bothAborted = outcomes.stream().allMatch(o -> o == Outcome.DEFINITIVELY_ABORTED); + if (ordering == Ordering.REVOKE_ORDER) { + return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING; + } + return outcomes.stream().allMatch(o -> o == Outcome.COMMITTED) + ? Settlement.COMMITTED + : Settlement.FAILED_NONPUBLICATION; + } + + private Record readOperation(UUID operation) { + return dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation); + } + + private Record readChange(UUID change) { + return dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ? FOR UPDATE", change); + } + + private Record requireExact(Record row, DraftAuthorizationFenceBinding binding) { + if (row == null + || !Arrays.equals(row.get("binding", byte[].class), binding.canonicalBytes()) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !binding.commitId().equals(row.get("commit_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class))) { + throw new IllegalArgumentException("Absent or changed immutable Draft operation"); + } + List sourceRows = + dsl + .fetch( + "SELECT source_key, source_evidence FROM " + SOURCES + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(Comparator.comparing(record -> record.get("source_key", String.class))) + .toList(); + if (sourceRows.size() != binding.sources().size()) { + throw new IllegalStateException("Incomplete source participation"); + } + for (int i = 0; i < sourceRows.size(); i++) { + SourceEvidence source = binding.sources().get(i); + if (!source.key().equals(sourceRows.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), sourceRows.get(i).get("source_evidence", byte[].class))) { + throw new IllegalStateException("Source participation differs from exact binding"); + } + } + return row; + } + + private void requireChange(Record row, SourceChange change) { + if (row == null || !Arrays.equals(row.get("binding", byte[].class), change.canonicalBytes())) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + List stored = + dsl + .fetch("SELECT source_key FROM " + CHANGED + " WHERE change_id = ?", change.changeId()) + .getValues("source_key", String.class) + .stream() + .sorted() + .toList(); + if (!stored.equals(change.sources().stream().map(SourceEvidence::key).toList())) { + throw new IllegalStateException("Incomplete source change participation"); + } + } + + private FenceSnapshot snapshot(Record row) { + return new FenceSnapshot( + Ordering.valueOf(row.get("ordering", String.class)), + row.get("binding", byte[].class), + row.get("reserved_at", OffsetDateTime.class), + row.get("ordered_at", OffsetDateTime.class)); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V57__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V57__draft_commit_authorization_fences.sql new file mode 100644 index 0000000000..e0fb5be03a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V57__draft_commit_authorization_fences.sql @@ -0,0 +1,167 @@ +-- Internal storage only. No source writer or authenticated authorization producer is enabled. +CREATE TABLE account_draft_authorization_source_locks ( + source_key VARCHAR(512) PRIMARY KEY CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512) +); + +CREATE TABLE account_draft_authorization_fences ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + fence_id UUID NOT NULL UNIQUE, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + ordering VARCHAR(20) NOT NULL CHECK (ordering IN ('RESERVED', 'COMMIT_ORDER', 'REVOKE_ORDER')), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ordered_at TIMESTAMPTZ, + CHECK ((ordering = 'RESERVED') = (ordered_at IS NULL)) +); + +CREATE TABLE account_draft_authorization_sources ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_draft_authorization_sources_by_scope + ON account_draft_authorization_sources(source_key, operation_id); + +CREATE TABLE account_draft_authorization_owner_readbacks ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'WORLD')), + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED')), + readback BYTEA NOT NULL CHECK (octet_length(readback) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, owner) +); + +CREATE TABLE account_draft_authorization_source_changes ( + change_id UUID PRIMARY KEY, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + CHECK ((status = 'WAITING') = (committed_at IS NULL)) +); + +CREATE TABLE account_draft_authorization_changed_scopes ( + change_id UUID NOT NULL REFERENCES account_draft_authorization_source_changes(change_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + PRIMARY KEY (change_id, source_key) +); +CREATE INDEX account_draft_authorization_changes_by_scope + ON account_draft_authorization_changed_scopes(source_key, change_id); + +-- [jooq ignore start] +CREATE FUNCTION account_draft_authorization_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Draft authorization evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_draft_authorization_order_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft authorization fence cannot be deleted'; + END IF; + IF OLD.ordering <> 'RESERVED' OR NEW.ordering NOT IN ('COMMIT_ORDER', 'REVOKE_ORDER') + OR NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.fence_id IS DISTINCT FROM OLD.fence_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.reserved_at IS DISTINCT FROM OLD.reserved_at + OR NEW.ordered_at IS NULL THEN + RAISE EXCEPTION 'Draft commit/revoke ordering is immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_source_change_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft source change cannot be deleted'; + END IF; + IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + OR NEW.change_id IS DISTINCT FROM OLD.change_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.requested_at IS DISTINCT FROM OLD.requested_at + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Draft source change result is immutable'; + END IF; + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_sources source USING (source_key) + JOIN account_draft_authorization_fences fence USING (operation_id) + WHERE changed.change_id = OLD.change_id + AND NOT ((fence.ordering = 'REVOKE_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + AND readback.outcome = 'DEFINITIVELY_ABORTED' + ) = 2) OR (fence.ordering = 'COMMIT_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + ) = 2)) + ) THEN + RAISE EXCEPTION 'Both definitive owner outcomes are required before source commit'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_insert_phase_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + phase TEXT; +BEGIN + IF TG_TABLE_NAME = 'account_draft_authorization_changed_scopes' THEN + SELECT status INTO phase FROM account_draft_authorization_source_changes + WHERE change_id = NEW.change_id FOR UPDATE; + IF phase IS DISTINCT FROM 'WAITING' THEN + RAISE EXCEPTION 'Completed source change cannot acquire new scopes'; + END IF; + ELSE + SELECT ordering INTO phase FROM account_draft_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_draft_authorization_sources' AND phase IS DISTINCT FROM 'RESERVED' THEN + RAISE EXCEPTION 'Ordered Draft operation cannot acquire new sources'; + ELSIF TG_TABLE_NAME = 'account_draft_authorization_owner_readbacks' + AND (phase IS NULL OR phase = 'RESERVED') THEN + RAISE EXCEPTION 'Reservation alone cannot produce owner terminal evidence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_draft_authorization_fence_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_fences + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_order_guard(); +CREATE TRIGGER account_draft_authorization_change_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_source_change_guard(); +CREATE TRIGGER account_draft_authorization_sources_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_readbacks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_scopes_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_locks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_locks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_insert_phase + BEFORE INSERT ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_readback_insert_phase + BEFORE INSERT ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_scope_insert_phase + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..5cab281b91 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,581 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Component fixtures stipulate authenticated current-source capture and authenticated definitive + * owner readback. They do not implement or prove those absent producers, RPC or source-writer + * gates. + */ +@Testcontainers(disabledWithoutDocker = true) +class DraftAuthorizationFencePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + Context restarted = + new Context( + context.dsl(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isFalse(); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat( + tx(restarted, () -> restarted.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertSourceGuardBlocked(restarted, change); + // Missing GD evidence models timeout/unavailable/absent owner row: no terminality is + // synthesized. + assertThat(tx(restarted, () -> restarted.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {5}); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isTrue(); + tx( + restarted, + () -> { + restarted.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(restarted, () -> restarted.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(restarted, () -> restarted.repository().claimCommitOrder(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + assertThatThrownBy( + () -> owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {22}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(committed.binding()).containsExactly(waiting.binding()); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var replay = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(replay.committedAt()).isEqualTo(committed.committedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {23})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var originalWorld = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + Outcome gameDesignOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.binding()).containsExactly(waiting.binding()); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var replay = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(replay.readback()).containsExactly(originalWorld.readback()); + assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + owner( + context, + binding, + Owner.GAME_DESIGN, + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED, + new byte[] {2}); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertSourceGuardBlocked(context, change); + } + } + + @Test + void changedCompleteBindingsConflictWithoutRewritingOriginal() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(); + var stored = tx(context, () -> context.repository().reserve(original)); + assertThat(tx(context, () -> context.repository().readSettlement(original))) + .isEqualTo(Settlement.PENDING); + for (int field = 0; field < 6; field++) { + DraftAuthorizationFenceBinding changed = changed(original, field); + assertThatThrownBy(() -> tx(context, () -> context.repository().reserve(changed))) + .isInstanceOf(IllegalArgumentException.class); + } + var replay = tx(context, () -> context.repository().reserve(original)); + assertThat(replay.binding()).containsExactly(stored.binding()); + assertThat(replay.reservedAt()).isEqualTo(stored.reservedAt()); + } + + @Test + void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { + Context context = context(); + DraftAuthorizationFenceBinding b = binding(); + for (int field = 0; field < 9; field++) { + int changedField = field; + byte[] bytes = field == 6 ? new byte[] {11} : b.gameDesignBinding(); + if (field == 8) { + bytes = + new String(bytes, StandardCharsets.UTF_8) + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8); + } + byte[] gameDesign = bytes; + byte[] input = field == 5 ? new byte[] {10} : gameDesign; + String digest = + field == 7 + ? DraftAuthorizationFenceBinding.digest(new byte[] {12}) + : DraftAuthorizationFenceBinding.digest(input); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .repository() + .reserve( + new DraftAuthorizationFenceBinding( + b.operationId(), + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + b.fenceId(), + b.actorAccountId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "different/base" : b.baseCommitId(), + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources())))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_sources"))) + .isZero(); + } + var stored = tx(context, () -> context.repository().reserve(b)); + assertThat(tx(context, () -> context.repository().reserve(b)).binding()) + .containsExactly(stored.binding()); + } + + @Test + void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().reserve(original); + context.repository().requestSourceChange(change(original)); + throw new IllegalStateException("injected rollback"); + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> tx(context, () -> context.repository().read(original))) + .isInstanceOf(IllegalArgumentException.class); + tx(context, () -> context.repository().reserve(original)); + tx(context, () -> context.repository().requestSourceChange(change(original))); + DraftAuthorizationFenceBinding independent = binding(); + tx(context, () -> context.repository().reserve(independent)); + assertThat(tx(context, () -> context.repository().claimCommitOrder(independent)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + } + + @Test + void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { + for (boolean commitWins : List.of(true, false)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + CountDownLatch firstOrdered = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> + tx( + context, + () -> { + if (commitWins) { + context.repository().claimCommitOrder(binding); + } else { + context.repository().requestSourceChange(change); + } + firstOrdered.countDown(); + await(secondStarted); + return null; + })); + var second = + executor.submit( + () -> { + await(firstOrdered); + secondStarted.countDown(); + if (commitWins) { + return tx(context, () -> context.repository().requestSourceChange(change)); + } + assertThatThrownBy( + () -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + return false; + }); + first.get(15, TimeUnit.SECONDS); + assertThat(second.get(15, TimeUnit.SECONDS)).isFalse(); + } + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(commitWins ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER); + } + } + + private void assertSourceGuardBlocked(Context context, SourceChange change) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + } + + private Context context() { + String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private DraftAuthorizationFenceBinding binding() { + UUID account = UUID.randomUUID(); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}); + DraftCommitBinding complete = + completeBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + "world-payload", + UUID.randomUUID()); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private DraftAuthorizationFenceBinding changed(DraftAuthorizationFenceBinding b, int field) { + SourceEvidence prior = b.sources().getFirst(); + SourceEvidence changedSource = + new SourceEvidence( + prior.kind(), + prior.scopeId(), + "4", + prior.sourceVersion(), + prior.checkpointStream(), + prior.checkpointSequence(), + prior.evidence()); + DraftCommitBinding priorComplete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + DraftCommitBinding complete = + completeBinding( + field == 1 ? UUID.randomUUID() : b.tenantId(), + field == 2 ? UUID.randomUUID() : b.versionId(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + field == 4 ? "changed-world-payload" : priorComplete.revisions().getFirst().payload(), + field == 5 ? UUID.randomUUID() : priorComplete.revisions().getFirst().revisionId()); + return new DraftAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + field == 0 ? UUID.randomUUID() : b.actorAccountId(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + b.baseCommitId(), + b.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + field == 3 ? List.of(changedSource) : b.sources()); + } + + private DraftCommitBinding completeBinding( + UUID tenant, + UUID version, + UUID request, + UUID commit, + String base, + String payload, + UUID revision) { + return DraftCommitBinding.create( + new TargetProof(tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + base, + List.of( + new RevisionPayload("0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, payload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + } + + private SourceChange change(DraftAuthorizationFenceBinding binding) { + return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + } + + private void owner( + Context context, + DraftAuthorizationFenceBinding b, + Owner owner, + Outcome outcome, + byte[] bytes) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + b.operationId(), + b.commitId(), + b.fenceId(), + b.inputDigest(), + b.canonicalBytes(), + bytes); + tx( + context, + () -> { + context.repository().recordOwnerReadback(b, readback); + return null; + }); + } + + private static T tx(Context context, Supplier work) { + return context.transaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Ordering fixture timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DSLContext dsl, + DraftAuthorizationFenceRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java new file mode 100644 index 0000000000..d912c83678 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java @@ -0,0 +1,398 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class DraftAuthorizationFenceBindingTest { + @Test + void copiedSourceListsAndEvidenceCannotRewriteBindingOrSourceChange() { + byte[] evidence = new byte[] {1, 2}; + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "2", "stream", "0", evidence); + List incoming = new ArrayList<>(List.of(source)); + DraftAuthorizationFenceBinding original = binding(source, "exact-payload"); + DraftAuthorizationFenceBinding captured = + new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + incoming); + SourceChange change = new SourceChange(UUID.randomUUID(), incoming, new byte[] {4}); + byte[] capturedBytes = captured.canonicalBytes(); + byte[] changedBytes = change.canonicalBytes(); + incoming.clear(); + evidence[0] = 99; + captured.sources().getFirst().evidence()[0] = 98; + change.sources().getFirst().evidence()[0] = 97; + assertThatThrownBy(() -> captured.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> change.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(captured.canonicalBytes()).containsExactly(capturedBytes); + assertThat(change.canonicalBytes()).containsExactly(changedBytes); + } + + @Test + void canonicalFramesPreserveIndependentCountersAndDefendExactBytes() { + byte[] evidence = "exact-source-proof".getBytes(StandardCharsets.UTF_8); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "9007199254740993", + "9007199254741007", + "account:source", + "17", + evidence); + DraftAuthorizationFenceBinding binding = binding(source, "normalized-input"); + byte[] gameDesign = binding.gameDesignBinding(); + byte[] input = binding.normalizedInput(); + DraftAuthorizationFenceBinding captured = + copy( + binding, + binding.requestId(), + binding.commitId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + gameDesign, + input, + binding.inputDigest()); + byte[] original = captured.canonicalBytes(); + evidence[0] = 0; + gameDesign[0] = 0; + input[0] = 0; + captured.normalizedInput()[0] = 0; + captured.gameDesignBinding()[0] = 0; + source.evidence()[0] = 0; + assertThat(captured.canonicalBytes()).containsExactly(original); + assertThat(captured.baseCommitId()).isEqualTo("opaque/base:9007199254740993"); + assertThat( + copy( + binding, + binding.requestId(), + binding.commitId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest()) + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(new String(original, StandardCharsets.UTF_8)) + .contains("9007199254740993", "9007199254741007", "17", binding.baseCommitId()); + } + + @Test + void nonexistentCounterApplicabilityIsNotManufacturedForGlobalRoleBirth() { + SourceEvidence source = + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + UUID.randomUUID().toString(), + null, + "1", + null, + null, + new byte[] {1}); + assertThat(source.generation()).isNull(); + assertThat(source.checkpointSequence()).isNull(); + assertThat(source.canonicalBytes()).isNotEmpty(); + } + + @Test + void rejectsOversizedMultibyteParticipationKeyWithoutChangingCanonicalScopes() { + String exactLimit = "界".repeat(168) + "x"; + SourceEvidence retained = + new SourceEvidence(SourceKind.ISSUER, exactLimit, "1", "1", "stream", "0", new byte[] {1}); + assertThat(retained.scopeId()).isEqualTo(exactLimit); + assertThat(retained.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ISSUER, exactLimit + "x", "1", "1", "stream", "0", new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + UUID account = UUID.randomUUID(); + SourceEvidence canonical = + new SourceEvidence( + SourceKind.ACCOUNT, account.toString(), "1", "2", "stream", "0", new byte[] {1}); + assertThat(canonical.scopeId()).isEqualTo(account.toString()); + assertThat(canonical.key()).isEqualTo("ACCOUNT:" + account); + } + + @Test + void rejectsAliasesNoncanonicalCountersAndChangedInputDigest() { + UUID id = UUID.randomUUID(); + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ACCOUNT, + id.toString().toUpperCase(), + "1", + "2", + "stream", + "3", + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + for (String counter : List.of("01", "1e3", "-1", " 1", "1.0")) { + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ACCOUNT, + id.toString(), + counter, + "2", + "stream", + "3", + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, id.toString(), "1", "2", "stream", "3", new byte[] {1}); + DraftAuthorizationFenceBinding binding = binding(source, "payload"); + assertThatThrownBy( + () -> + new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + "0", + binding.gameDesignBinding(), + new byte[] {2}, + binding.inputDigest(), + List.of(source))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedDuplicatedIdentitiesAndBaseBeforeStorage() { + DraftAuthorizationFenceBinding b = binding(source(), "payload"); + for (int field = 0; field < 5; field++) { + int changedField = field; + assertThatThrownBy( + () -> + copy( + b, + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "changed/base" : b.baseCommitId(), + b.gameDesignBinding(), + b.normalizedInput(), + b.inputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + for (String invalidBase : List.of("", " ", "x".repeat(257), "界".repeat(86))) { + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + invalidBase, + b.gameDesignBinding(), + b.normalizedInput(), + b.inputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsMalformedNoncanonicalOrReorderedGameDesignBytesAndAlternateInput() { + DraftAuthorizationFenceBinding b = binding(source(), "payload"); + DraftCommitBinding complete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + List reordered = new ArrayList<>(complete.revisions()); + java.util.Collections.reverse(reordered); + List invalid = + List.of( + new byte[] {3}, + new byte[] {(byte) 0xff}, + (complete.canonicalJson() + " ").getBytes(StandardCharsets.UTF_8), + complete + .canonicalJson() + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8)); + for (byte[] bytes : invalid) { + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + bytes, + bytes, + DraftAuthorizationFenceBinding.digest(bytes))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + reordered, + complete.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class); + byte[] alternate = "alternate-input".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + b.gameDesignBinding(), + alternate, + DraftAuthorizationFenceBinding.digest(alternate))) + .isInstanceOf(IllegalArgumentException.class); + DraftCommitBinding changed = + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + List.of( + new RevisionPayload( + "0", + complete.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "changed-payload"), + complete.revisions().get(1)), + complete.affectedUnits()); + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + changed.canonicalBytes(), + b.normalizedInput(), + changed.digest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private SourceEvidence source() { + return new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "2", "stream", "0", new byte[] {1}); + } + + private DraftAuthorizationFenceBinding copy( + DraftAuthorizationFenceBinding b, + UUID request, + UUID commit, + UUID tenant, + UUID version, + String base, + byte[] gameDesign, + byte[] input, + String digest) { + return new DraftAuthorizationFenceBinding( + b.operationId(), + request, + commit, + b.fenceId(), + b.actorAccountId(), + tenant, + version, + base, + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources()); + } + + private DraftAuthorizationFenceBinding binding(SourceEvidence source, String payload) { + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + List.of( + new RevisionPayload("0", UUID.randomUUID(), Owner.WORLD_MANAGEMENT, payload), + new RevisionPayload( + "1", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "control")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "version", + "version-1", + "aggregate", + "version-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "9007199254741009", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java new file mode 100644 index 0000000000..e8ee145a51 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java @@ -0,0 +1,454 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +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.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete immutable Game Design binding for one coordinated Draft commit. + * + *

This type retains a declared mutation and its affected tuple set exactly. Its owner labels and + * opaque payloads are not proof that the declaration is semantically complete; each typed owner + * producer must derive and verify its required tuple subset before any owner action. + */ +public final class DraftCommitBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator AFFECTED_ORDER = + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId); + + /** Owners participating in the canonical multi-owner Draft commit contract. */ + public enum Owner { + WORLD_MANAGEMENT, + ENTITY_MANAGEMENT, + GAME_LOGIC, + AUTOMATION_SCRIPTING, + GAME_DESIGN_CONTROL_PLANE + } + + /** Canonical identity plus the exact private Game Design Version/source lineage. */ + public record TargetProof( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) { + public TargetProof { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (gameDesignVersionRowId <= 0 || sourceGameRowId <= 0) { + throw new IllegalArgumentException("Game Design source row identities must be positive"); + } + requireBoundedText(gameDesignVersionTenantKey, 36, "gameDesignVersionTenantKey"); + requireBoundedText(sourceGameTenantKey, 36, "sourceGameTenantKey"); + if (!gameDesignVersionTenantKey.equals(sourceGameTenantKey)) { + throw new IllegalArgumentException( + "Version and source Game Design tenant keys must match exactly"); + } + if (!"NEW_GAME_ROW".equals(sourceProvenanceKind) + && !"RETAINED_GAME_V30".equals(sourceProvenanceKind)) { + throw new IllegalArgumentException("Unsupported canonical Version source provenance"); + } + } + } + + /** One full owner-typed revision payload. The payload is opaque and is never normalized here. */ + public record RevisionPayload( + String revisionOrder, UUID revisionId, Owner owner, String payload) { + public RevisionPayload { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(payload, "payload"); + } + } + + /** The expected epoch for one owner-local aggregate and scope fence. */ + public record AffectedUnit( + Owner owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public AffectedUnit { + Objects.requireNonNull(owner, "owner"); + requireBoundedText(aggregateType, 128, "aggregateType"); + requireBoundedText(aggregateId, 256, "aggregateId"); + requireBoundedText(scopeType, 128, "scopeType"); + requireBoundedText(scopeId, 256, "scopeId"); + requireCanonicalCounter(expectedEpoch, "expectedEpoch"); + } + } + + private final TargetProof target; + private final UUID requestId; + private final UUID commitId; + private final String baseCommitId; + private final List revisions; + private final List affectedUnits; + private final List requiredOwners; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private DraftCommitBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + this.target = Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + requireBoundedText(baseCommitId, 256, "baseCommitId"); + this.requestId = requestId; + this.commitId = commitId; + this.baseCommitId = baseCommitId; + this.revisions = validateRevisions(revisions); + this.affectedUnits = validateAffectedUnits(affectedUnits); + this.requiredOwners = validateOwnerCoverage(this.revisions, this.affectedUnits); + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialize(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft commit binding could not be canonicalized", exception); + } + } + + public static DraftCommitBinding create( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + return new DraftCommitBinding( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + /** Reconstructs an immutable binding from owner storage and rejects noncanonical/corrupt rows. */ + public static DraftCommitBinding fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + JsonNode targetNode = requireObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(root, "canonicalTenantId")), + UUID.fromString(requiredText(root, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + List revisions = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "revisions")) { + revisions.add( + new RevisionPayload( + requiredText(node, "revisionOrder"), + UUID.fromString(requiredText(node, "revisionId")), + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "payload"))); + } + List affectedUnits = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "affectedUnits")) { + affectedUnits.add( + new AffectedUnit( + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"))); + } + DraftCommitBinding binding = + create( + target, + UUID.fromString(requiredText(root, "requestId")), + UUID.fromString(requiredText(root, "commitId")), + requiredText(root, "baseCommitId"), + revisions, + affectedUnits); + if (!binding.canonicalJson.equals(storedJson) + || !binding.digest.equals(storedDigest) + || !Arrays.equals(binding.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored Draft commit binding is not exact canonical JSON"); + } + return binding; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Draft commit binding is corrupt", exception); + } + } + + public TargetProof target() { + return target; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public String baseCommitId() { + return baseCommitId; + } + + public List revisions() { + return List.copyOf(revisions); + } + + public List affectedUnits() { + return List.copyOf(affectedUnits); + } + + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + /** The canonical UTF-8 representation, retained as text for exact database equality. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a defensive copy of the exact RFC 8785 bytes stored with this binding. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public List affectedUnits(Owner owner) { + return affectedUnits.stream().filter(unit -> unit.owner() == owner).toList(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftCommitBinding binding + && digest.equals(binding.digest) + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map object = new LinkedHashMap<>(); + object.put("schemaVersion", "1"); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + Map targetObject = new LinkedHashMap<>(); + targetObject.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + targetObject.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + targetObject.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + targetObject.put("sourceGameTenantKey", target.sourceGameTenantKey()); + targetObject.put("sourceProvenanceKind", target.sourceProvenanceKind()); + object.put("target", targetObject); + object.put("requestId", requestId.toString()); + object.put("commitId", commitId.toString()); + object.put("baseCommitId", baseCommitId); + object.put("revisions", revisions.stream().map(DraftCommitBinding::revisionJson).toList()); + object.put( + "affectedUnits", affectedUnits.stream().map(DraftCommitBinding::affectedUnitJson).toList()); + object.put("requiredOwners", requiredOwners.stream().map(Enum::name).toList()); + return object; + } + + private static Map revisionJson(RevisionPayload revision) { + Map object = new LinkedHashMap<>(); + object.put("revisionOrder", revision.revisionOrder()); + object.put("revisionId", revision.revisionId().toString()); + object.put("owner", revision.owner().name()); + object.put("payload", revision.payload()); + return object; + } + + private static Map affectedUnitJson(AffectedUnit unit) { + Map object = new LinkedHashMap<>(); + object.put("owner", unit.owner().name()); + object.put("aggregateType", unit.aggregateType()); + object.put("aggregateId", unit.aggregateId()); + object.put("scopeType", unit.scopeType()); + object.put("scopeId", unit.scopeId()); + object.put("expectedEpoch", unit.expectedEpoch()); + return object; + } + + private static List validateRevisions(List requested) { + Objects.requireNonNull(requested, "revisions"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must contain at least one full revision"); + } + List copy = List.copyOf(requested); + Set revisionIds = new HashSet<>(); + for (int index = 0; index < copy.size(); index++) { + RevisionPayload revision = Objects.requireNonNull(copy.get(index), "revision"); + if (!Integer.toString(index).equals(revision.revisionOrder())) { + throw new IllegalArgumentException( + "Revision order must be the contiguous canonical array order"); + } + if (!revisionIds.add(revision.revisionId())) { + throw new IllegalArgumentException("Draft commit contains a duplicate revision identity"); + } + if (revision.payload().isEmpty()) { + throw new IllegalArgumentException("A full revision payload must not be omitted"); + } + } + return copy; + } + + private static List validateAffectedUnits(List requested) { + Objects.requireNonNull(requested, "affectedUnits"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must declare its complete affected units"); + } + List copy = new ArrayList<>(requested.size()); + Set identities = new HashSet<>(); + for (AffectedUnit unit : requested) { + Objects.requireNonNull(unit, "affectedUnit"); + String identity = + unit.owner() + + "\u0000" + + unit.aggregateType() + + "\u0000" + + unit.aggregateId() + + "\u0000" + + unit.scopeType() + + "\u0000" + + unit.scopeId(); + if (!identities.add(identity)) { + throw new IllegalArgumentException( + "Draft commit contains a duplicate affected owner scope"); + } + copy.add(unit); + } + copy.sort(AFFECTED_ORDER); + return List.copyOf(copy); + } + + private static List validateOwnerCoverage( + List revisions, List affectedUnits) { + Set revisionOwners = new HashSet<>(); + revisions.forEach(revision -> revisionOwners.add(revision.owner())); + Set affectedOwners = new HashSet<>(); + affectedUnits.forEach(unit -> affectedOwners.add(unit.owner())); + if (!revisionOwners.equals(affectedOwners)) { + throw new IllegalArgumentException( + "Required owner set must exactly match owners derived from revisions and affected units"); + } + return Arrays.stream(Owner.values()).filter(revisionOwners::contains).toList(); + } + + private static String serialize(Object object) { + return JSON.writeValueAsString(object); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing text field " + field); + } + return value.textValue(); + } + + private static JsonNode requireObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing object field " + field); + } + return value; + } + + private static JsonNode requiredArray(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing array field " + field); + } + return value; + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireCanonicalCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + new BigInteger(value); + } + + private static void requireBoundedText(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank canonical bounded text"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java new file mode 100644 index 0000000000..5ff59fe7d1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable exact selection of an existing synchronized authored Draft for full-version + * publication. This is retained selection evidence, not authorization, owner freeze, or release + * evidence. + */ +public final class AuthoredDraftPublishSelection { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final PublishIntent intent; + private final TargetProof target; + private final DraftCommitBinding selectedCommit; + private final UUID fenceRequestId; + private final UUID fenceCommitId; + private final String fenceInputDigest; + private final String fenceResultVectorJson; + private final String fenceCreatedAt; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredDraftPublishSelection( + PublishIntent intent, + TargetProof target, + DraftCommitBinding selectedCommit, + VisibilityFence fence) { + this.intent = Objects.requireNonNull(intent, "intent"); + this.target = Objects.requireNonNull(target, "target"); + this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(fence, "fence"); + if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !target.equals(selectedCommit.target()) + || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) + || !intent.selectedCommitId().equals(selectedCommit.commitId()) + || !intent.selectedCommitDigest().equals(selectedCommit.digest()) + || !target.equals(fence.target()) + || !intent.selectedCommitRequestId().equals(fence.requestId()) + || !intent.selectedCommitId().equals(fence.commitId()) + || !intent.selectedCommitDigest().equals(fence.inputDigest())) { + throw new IllegalArgumentException( + "Authored Draft publication selection differs from its exact synchronized commit fence"); + } + requireCanonicalArray(fence.resultVectorJson()); + this.fenceRequestId = fence.requestId(); + this.fenceCommitId = fence.commitId(); + this.fenceInputDigest = fence.inputDigest(); + this.fenceResultVectorJson = fence.resultVectorJson(); + this.fenceCreatedAt = fence.createdAt().toInstant().toString(); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Authored Draft publication selection could not be canonicalized", exception); + } + } + + /** + * Constructs the exact retained value after the repository has independently verified the locked + * Version, durable commit, owner result vector, and current visibility fence. + */ + public static AuthoredDraftPublishSelection capture( + PublishIntent intent, TargetProof target, PublicationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return new AuthoredDraftPublishSelection( + intent, target, evidence.binding(), evidence.visibilityFence()); + } + + /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ + public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported authored Draft selection schema"); + } + JsonNode intentNode = requiredObject(root, "intent"); + PublishIntent intent = + new PublishIntent( + UUID.fromString(requiredText(intentNode, "canonicalTenantId")), + UUID.fromString(requiredText(intentNode, "canonicalVersionId")), + requiredText(intentNode, "publishRequestId"), + requiredText(intentNode, "expectedVersionStateEpoch"), + requiredText(intentNode, "notes"), + UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), + UUID.fromString(requiredText(intentNode, "selectedCommitId")), + requiredText(intentNode, "selectedCommitDigest")); + JsonNode targetNode = requiredObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(targetNode, "canonicalTenantId")), + UUID.fromString(requiredText(targetNode, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + DraftCommitBinding selectedCommit = + DraftCommitBinding.fromStored( + requiredText(root, "selectedCommitBindingJson"), + requiredText(root, "selectedCommitDigest")); + JsonNode fenceNode = requiredObject(root, "synchronizedFence"); + String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); + requireCanonicalArray(fenceResultVectorJson); + VisibilityFence fence = + new VisibilityFence( + target, + UUID.fromString(requiredText(fenceNode, "requestId")), + UUID.fromString(requiredText(fenceNode, "commitId")), + requiredText(fenceNode, "inputDigest"), + fenceResultVectorJson, + OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); + AuthoredDraftPublishSelection selection = + new AuthoredDraftPublishSelection(intent, target, selectedCommit, fence); + if (!selection.canonicalJson.equals(storedJson) + || !selection.digest.equals(storedDigest) + || !Arrays.equals( + selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored authored Draft publication selection is not exact canonical JSON"); + } + return selection; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); + } + } + + public PublishIntent intent() { + return intent; + } + + public TargetProof target() { + return target; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public UUID fenceRequestId() { + return fenceRequestId; + } + + public UUID fenceCommitId() { + return fenceCommitId; + } + + public String fenceInputDigest() { + return fenceInputDigest; + } + + public String fenceResultVectorJson() { + return fenceResultVectorJson; + } + + public String fenceCreatedAt() { + return fenceCreatedAt; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelection selection + && digest.equals(selection.digest) + && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "1"); + root.put("intent", intentJson(intent)); + root.put("target", targetJson(target)); + root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); + root.put("selectedCommitDigest", selectedCommit.digest()); + Map fence = new LinkedHashMap<>(); + fence.put("requestId", fenceRequestId.toString()); + fence.put("commitId", fenceCommitId.toString()); + fence.put("inputDigest", fenceInputDigest); + fence.put("resultVectorJson", fenceResultVectorJson); + fence.put("createdAt", fenceCreatedAt); + root.put("synchronizedFence", fence); + return root; + } + + private static Map intentJson(PublishIntent intent) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", intent.canonicalTenantId().toString()); + object.put("canonicalVersionId", intent.canonicalVersionId().toString()); + object.put("publishRequestId", intent.publishRequestId()); + object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); + object.put("notes", intent.notes()); + object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); + object.put("selectedCommitId", intent.selectedCommitId().toString()); + object.put("selectedCommitDigest", intent.selectedCommitDigest()); + return object; + } + + private static Map targetJson(TargetProof target) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + object.put("sourceGameTenantKey", target.sourceGameTenantKey()); + object.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return object; + } + + private static JsonNode requiredObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing object field " + field); + } + return value; + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing text field " + field); + } + return value.textValue(); + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireCanonicalArray(String storedJson) { + try { + JsonNode node = JSON.readTree(storedJson); + if (node == null || !node.isArray()) { + throw new IllegalArgumentException("Stored owner result vector is not an array"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); + if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); + } + } catch (IOException exception) { + throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + PublicationDigestRequestBinding.validatePublicationIdentity( + canonicalTenantId.toString(), publishRequestId); + requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); + Objects.requireNonNull(notes, "notes"); + requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireDigest(selectedCommitDigest, "selectedCommitDigest"); + } + } + + private static void requirePositiveCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); + } + } + + private static void requireDigest(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java new file mode 100644 index 0000000000..5729cbf0a8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitStateConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.LockedVersion; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Retains the first exact authored-Draft selection for a full-version publication request. The + * durable row is a reservation; this repository does not release it or infer any World freeze or + * terminal participant outcome. Later workflow code must recover the same selection and persist + * only definitive authenticated owner readback in its separately owned boundary. + */ +@Repository +public class AuthoredDraftPublishSelectionRepository { + private static final String SELECTION_TABLE = "game_design_authored_draft_publish_selection"; + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborators only; no resources are acquired and no finalizer is used.") + public AuthoredDraftPublishSelectionRepository( + DSLContext dsl, DraftCommitCoordinatorRepository coordinator) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.coordinator = Objects.requireNonNull(coordinator, "coordinator"); + } + + /** + * Selects exactly one caller-named current synchronized commit for an existing full Draft + * Version. Exact request replay returns the immutable first selection before reading mutable + * Version state or current-fence state again. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public SelectionSnapshot reserve(PublishIntent intent) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(intent, "intent"); + + LockedVersion version = + coordinator.lockVersionTarget(intent.canonicalTenantId(), intent.canonicalVersionId()); + SelectionSnapshot existing = findByTarget(version.target(), false); + if (existing != null) { + requireExactIntent(intent, existing.selection().intent()); + return existing; + } + + requireEligibleFirstSelection(version, intent); + if (coordinator.readApplicationSlot(version.target()).isPresent()) { + throw new DraftCommitStateConflictException( + "An active or unresolved owner application prevents Draft publication selection"); + } + PublicationEvidence evidence = + coordinator.requireSynchronizedPublicationEvidence( + version.target(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture(intent, version.target(), evidence); + + int inserted; + try { + inserted = insert(selection); + } catch (DataAccessException exception) { + if (isUniqueConstraintViolation(exception)) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publication selection already reserves this Version", exception); + } + throw exception; + } + SelectionSnapshot persisted = findByTarget(version.target(), false); + if (persisted == null) { + throw new IllegalStateException( + "Durable authored Draft publication selection disappeared after insert"); + } + requireExactIntent(intent, persisted.selection().intent()); + if (inserted == 0 && !selection.equals(persisted.selection())) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publish request was reused with changed exact binding data"); + } + return persisted; + } + + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional read( + UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + canonicalTenantId, + canonicalVersionId); + if (row == null || !publishRequestId.equals(row.get("publish_request_id", String.class))) { + return Optional.empty(); + } + return Optional.of(toSnapshot(row)); + } + + private int insert(AuthoredDraftPublishSelection selection) { + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + return dsl.execute( + "INSERT INTO " + + SELECTION_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, publish_request_id, version_state_epoch, " + + "selected_commit_request_id, selected_commit_id, selected_commit_digest, " + + "selection_digest, selection_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selection.digest(), + selection.canonicalJson()); + } + + private SelectionSnapshot findByTarget(TargetProof target, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? null : toSnapshot(row); + } + + private SelectionSnapshot toSnapshot(Record row) { + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.fromStored( + row.get("selection_json", String.class), row.get("selection_digest", String.class)); + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + if (!row.get("canonical_tenant_id", UUID.class).equals(target.canonicalTenantId()) + || !row.get("canonical_version_id", UUID.class).equals(target.canonicalVersionId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(target.gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(target.gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(target.sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class).equals(target.sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class).equals(target.sourceProvenanceKind()) + || !row.get("publish_request_id", String.class).equals(intent.publishRequestId()) + || !Long.toString(row.get("version_state_epoch", Long.class)) + .equals(intent.expectedVersionStateEpoch()) + || !row.get("selected_commit_request_id", UUID.class) + .equals(intent.selectedCommitRequestId()) + || !row.get("selected_commit_id", UUID.class).equals(intent.selectedCommitId()) + || !row.get("selected_commit_digest", String.class).equals(intent.selectedCommitDigest())) { + throw new IllegalStateException( + "Authored Draft publication selection indexed identity differs from exact stored binding"); + } + return new SelectionSnapshot(selection, row.get("created_at", OffsetDateTime.class)); + } + + private static void requireEligibleFirstSelection(LockedVersion version, PublishIntent intent) { + if (!"DRAFT".equals(version.versionState()) + || version.scriptOnly() + || version.scriptPatchVersion() != null + || version.baseVersionId() != null) { + throw new DraftCommitStateConflictException( + "Only an existing non-script-only full Version in DRAFT can be selected for publication"); + } + if (!Long.toString(version.versionStateEpoch()).equals(intent.expectedVersionStateEpoch())) { + throw new DraftCommitStateConflictException( + "Authored Draft publication selection has a stale Version state epoch"); + } + } + + private static void requireExactIntent(PublishIntent expected, PublishIntent actual) { + if (!expected.equals(actual)) { + throw new DraftCommitIdentityConflictException( + "Publish request identity was reused with changed notes, target, epoch, or commit selection"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Authored Draft selection mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static boolean isUniqueConstraintViolation(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState())) { + return true; + } + current = current.getCause(); + } + return false; + } + + public record SelectionSnapshot( + AuthoredDraftPublishSelection selection, OffsetDateTime createdAt) { + public SelectionSnapshot { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java new file mode 100644 index 0000000000..5cacfc337b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -0,0 +1,1611 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** Durable, owner-local persistence for exact Game Design multi-owner Draft commit coordination. */ +@Repository +public class DraftCommitCoordinatorRepository { + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String OWNER_RESULT_TABLE = "game_design_draft_commit_owner_result"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + private static final String APPLICATION_SLOT_TABLE = "game_design_draft_commit_application_slot"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String VISIBILITY_TABLE = "game_design_draft_commit_visibility"; + private static final String PUBLISH_SELECTION_TABLE = + "game_design_authored_draft_publish_selection"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Comparator APPLIED_EPOCH_ORDER = + Comparator.comparing(AppliedEpoch::aggregateType) + .thenComparing(AppliedEpoch::aggregateId) + .thenComparing(AppliedEpoch::scopeType) + .thenComparing(AppliedEpoch::scopeId); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborator only; no resources are acquired and no finalizer is used.") + public DraftCommitCoordinatorRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Durably claims one complete immutable request binding and initializes every required owner. An + * exact replay performs no writes; either identity reused with changed binding data conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + CommitRecord existing = findCommit(binding, true); + if (existing != null) { + requireExactBinding(binding, existing.binding()); + return snapshot(existing); + } + + int inserted; + try { + inserted = + dsl.execute( + "INSERT INTO " + + COMMIT_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, request_id, commit_id, base_commit_id, input_digest, " + + "binding_json, workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'QUEUED') " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id) DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.target().gameDesignVersionRowId(), + binding.target().gameDesignVersionTenantKey(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); + } catch (DataAccessException exception) { + if (isUniqueConstraintViolation(exception)) { + throw new DraftCommitIdentityConflictException( + "Draft commit request or commit identity is already bound to different input", + exception); + } + throw exception; + } + + if (inserted == 0) { + CommitRecord concurrent = findCommit(binding, true); + if (concurrent == null) { + throw new DraftCommitIdentityConflictException( + "Draft commit identity conflicts with another immutable request"); + } + requireExactBinding(binding, concurrent.binding()); + return snapshot(concurrent); + } + + for (Owner owner : binding.requiredOwners()) { + dsl.execute( + "INSERT INTO " + + OWNER_RESULT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, owner, status) " + + "VALUES (?, ?, ?, ?, 'NOT_ATTEMPTED')", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + } + CommitRecord persisted = findCommit(binding, true); + if (persisted == null) { + throw new IllegalStateException("Durable Draft commit binding disappeared after insert"); + } + requireExactBinding(binding, persisted.binding()); + return snapshot(persisted); + } + + /** Reads one durable binding and its exact per-owner status vector. */ + public Optional read(DraftCommitBinding.TargetProof target, UUID requestId) { + requireTargetAndRequest(target, requestId); + CommitRecord record = findCommit(target, requestId, false); + return record == null ? Optional.empty() : Optional.of(snapshot(record)); + } + + /** Reads the current active dispatch/recovery slot for one canonical Version. */ + public Optional readApplicationSlot(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record record = findSlot(target, false); + return record == null ? Optional.empty() : Optional.of(toApplicationSlot(record)); + } + + /** + * Claims the single active owner-application slot for this canonical Version. The persisted + * binding remains queued if another exact commit currently owns the slot. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public ApplicationSlot claimApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + LockedVersion version = lockVersionTarget(binding.target()); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + CommitRecord commit = findCommit(binding, true); + if (commit == null) { + throw new DraftCommitNotFoundException( + "Draft commit must be durably claimed before slot claim"); + } + requireExactBinding(binding, commit.binding()); + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "A terminal Draft commit cannot reclaim its slot"); + } + Record existing = findSlot(binding.target(), true); + if (existing != null) { + ApplicationSlot slot = toApplicationSlot(existing); + requireSameSlot(binding, slot); + return slot; + } + int inserted = + dsl.execute( + "INSERT INTO " + + APPLICATION_SLOT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + Record persisted = findSlot(binding.target(), true); + if (persisted == null) { + throw new DraftCommitStateConflictException( + "Another coordinated Draft commit currently owns the Version application slot"); + } + ApplicationSlot slot = toApplicationSlot(persisted); + requireSameSlot(binding, slot); + if (inserted == 1 && slot.claimedAt() == null) { + throw new IllegalStateException("Draft commit application slot lacks durable claim time"); + } + return slot; + } + + /** Marks an owner dispatch in progress before the caller makes any remote owner call. */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState markOwnerInProgress(DraftCommitBinding binding, Owner owner) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireExactCommitInTransaction(binding); + requireActiveSlot(binding); + OwnerState current = requireOwnerState(binding, owner, true); + if (current.status() == OwnerStatus.IN_PROGRESS) { + return current; + } + if (current.status() != OwnerStatus.NOT_ATTEMPTED) { + throw new DraftCommitStateConflictException( + "Only a not-yet-attempted owner can enter IN_PROGRESS"); + } + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = 'IN_PROGRESS', updated_at = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = 'NOT_ATTEMPTED'", + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner status changed concurrently"); + } + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + } + return requireOwnerState(binding, owner, false); + } + + /** + * Retains one full owner result. UNKNOWN remains unresolved and can only be resolved through an + * exact later APPLIED/REJECTED result for the same commit and binding digest. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState recordOwnerOutcome(DraftCommitBinding binding, OwnerOutcome outcome) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(outcome, "outcome"); + LockedVersion version = lockVersionTarget(binding.target()); + requireExactCommitInTransaction(binding); + requireOutcomeMatches(binding, outcome); + OwnerState current = requireOwnerState(binding, outcome.owner(), true); + if (current.outcome().filter(outcome::equals).isPresent()) { + return current; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + if (current.status() != OwnerStatus.IN_PROGRESS && current.status() != OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "A Draft owner outcome cannot replace its durable prior result"); + } + if (current.status() == OwnerStatus.UNKNOWN && outcome.status() == OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "UNKNOWN remains unresolved until exact owner readback supplies a terminal result"); + } + String appliedUnitsJson = + outcome.status() == OwnerStatus.UNKNOWN + ? null + : canonicalJson(outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = ?, result_commit_id = ?, result_binding_digest = ?, " + + "result_identity = ?, result_bytes = ?, applied_units_json = ?, updated_at = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = ?", + outcome.status().name(), + outcome.commitId(), + outcome.bindingDigest(), + outcome.resultIdentity(), + outcome.resultBytes(), + appliedUnitsJson, + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + outcome.owner().name(), + current.status().name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner result changed concurrently"); + } + updateWorkflowStateAfterOwnerOutcome(binding, outcome); + return requireOwnerState(binding, outcome.owner(), false); + } + + /** + * Advances the internal synchronized visibility record only from the complete exact APPLIED + * result vector. This storage primitive is intentionally not wired to an owner producer or read + * API; callers must validate each remote producer's authority before invoking it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(coordinatorProof, "coordinatorProof"); + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + if (!coordinatorProof.matches(binding)) { + throw new DraftCommitIdentityConflictException( + "Visibility fence requires coordinator proof for this exact Draft binding"); + } + List ownerStates = lockAndReadOwnerStates(binding); + coordinatorProof.requireSameOutcomes(ownerStates); + String resultVectorJson = exactAppliedResultVector(binding, ownerStates); + VisibilityFence existing = findVisibilityFence(binding, false); + if (existing != null) { + if (!existing.inputDigest().equals(binding.digest()) + || !existing.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A Draft commit visibility fence already retains different owner evidence"); + } + return existing; + } + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Terminal Draft commit has no matching immutable visibility fence"); + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + int inserted = + dsl.execute( + "INSERT INTO " + + VISIBILITY_FENCE_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + resultVectorJson); + VisibilityFence persisted = findVisibilityFence(binding, false); + if (persisted == null) { + throw new IllegalStateException("Draft visibility fence insert returned no persisted row"); + } + if (inserted == 0) { + if (!persisted.inputDigest().equals(binding.digest()) + || !persisted.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A concurrent Draft visibility fence retained different owner evidence"); + } + return persisted; + } + dsl.execute( + "INSERT INTO " + + VISIBILITY_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (canonical_tenant_id, canonical_version_id) " + + "DO UPDATE SET request_id = EXCLUDED.request_id, commit_id = EXCLUDED.commit_id, " + + "input_digest = EXCLUDED.input_digest, updated_at = EXCLUDED.updated_at", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest()); + updateWorkflowState(binding, WorkflowState.SYNCHRONIZED); + return persisted; + } + + /** + * Reads the current internal visibility pointer without claiming that downstream reads use it. + */ + public Optional readVisibilityFence(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record pointer = + dsl.fetchOne( + "SELECT request_id, commit_id FROM " + + VISIBILITY_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (pointer == null) { + return Optional.empty(); + } + UUID requestId = pointer.get("request_id", UUID.class); + UUID commitId = pointer.get("commit_id", UUID.class); + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + if (fence == null) { + throw new IllegalStateException("Draft visibility pointer lacks its immutable fence record"); + } + return Optional.of(toVisibilityFence(target, requestId, commitId, fence)); + } + + /** + * Captures only an explicitly selected current synchronized commit while the caller's publication + * transaction owns the exact Version row lock. It does not authorize publication or assert any + * remote freeze/participant result. + */ + PublicationEvidence requireSynchronizedPublicationEvidence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, String inputDigest) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(target); + requireDraftVersion(version); + if (findSlot(target, false) != null) { + throw new DraftCommitStateConflictException( + "An active owner application prevents authored Draft publication selection"); + } + + CommitRecord commit = findCommit(target, requestId, true); + if (commit == null + || !commit.binding().commitId().equals(commitId) + || !commit.binding().digest().equals(inputDigest)) { + throw new DraftCommitIdentityConflictException( + "Selected authored Draft commit identity or digest does not match durable input"); + } + if (commit.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "Only an explicitly selected synchronized authored Draft commit can be published"); + } + List ownerStates = lockAndReadOwnerStates(commit.binding()); + String exactVector = exactAppliedResultVector(commit.binding(), ownerStates); + VisibilityFence fence = findVisibilityFence(commit.binding(), true); + if (fence == null + || !fence.inputDigest().equals(inputDigest) + || !fence.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit lacks its exact complete synchronized result fence"); + } + VisibilityFence current = + readVisibilityFence(target) + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Selected authored Draft commit is not the current synchronized fence")); + if (!current.requestId().equals(requestId) + || !current.commitId().equals(commitId) + || !current.inputDigest().equals(inputDigest) + || !current.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit is stale relative to the current synchronized fence"); + } + return new PublicationEvidence(commit.binding(), fence); + } + + /** + * Releases the Version application slot after complete success, definite no-application + * rejection, or exact final-abort evidence with every owner definitive. Unresolved outcomes and + * partial application without that final-abort proof keep the slot held. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public void releaseApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + Record slotRecord = findSlot(binding.target(), true); + if (commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + requireFinalAbortSlotRelease(binding, commit); + if (slotRecord == null || !isSameSlot(binding, toApplicationSlot(slotRecord))) { + return; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + deleteApplicationSlot(binding); + return; + } + if (slotRecord == null) { + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED) { + return; + } + throw new DraftCommitStateConflictException( + "Draft commit does not own the active Version slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + List outcomes = lockAndReadOwnerStates(binding); + boolean anyApplied = outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean unresolved = + outcomes.stream() + .anyMatch( + state -> + state.status() == OwnerStatus.UNKNOWN + || state.status() == OwnerStatus.IN_PROGRESS); + boolean allApplied = outcomes.stream().allMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean definiteNoApply = + outcomes.stream() + .allMatch( + state -> + state.status() == OwnerStatus.NOT_ATTEMPTED + || state.status() == OwnerStatus.REJECTED) + && outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + if (unresolved || (anyApplied && !allApplied) || (!allApplied && !definiteNoApply)) { + throw new DraftCommitStateConflictException( + "Unresolved or partially applied Draft commit cannot release its Version slot"); + } else if (allApplied) { + VisibilityFence fence = findVisibilityFence(binding, false); + if (commit.workflowState() != WorkflowState.SYNCHRONIZED + || fence == null + || !fence.inputDigest().equals(binding.digest())) { + throw new DraftCommitStateConflictException( + "All-owner Draft application must have its exact synchronized visibility fence first"); + } + } else if (definiteNoApply) { + if (anyApplied) { + throw new DraftCommitStateConflictException( + "A rejected Draft commit with any applied owner requires reconciliation"); + } + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Definite rejected Draft commit is not in an applicable workflow state"); + } + updateWorkflowState(binding, WorkflowState.REJECTED); + } + deleteApplicationSlot(binding); + } + + private void deleteApplicationSlot(DraftCommitBinding binding) { + int deleted = + dsl.execute( + "DELETE FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (deleted != 1) { + throw new DraftCommitStateConflictException( + "Draft Version application slot changed concurrently"); + } + } + + /** + * Stores exact, already-authenticated producer no-commit evidence for a definitive owner vector + * and atomically makes this commit terminally non-publishable. This storage method does not + * authenticate arbitrary bytes; only a future authenticated recovery producer may call it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FinalAbortReceipt recordDefinitiveFinalAbort( + DraftCommitBinding binding, byte[] exactAbortBytes) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(exactAbortBytes, "exactAbortBytes"); + if (exactAbortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + Record slotRecord = findSlot(binding.target(), true); + Record existingAbort = findFinalAbort(binding, true); + if (existingAbort != null) { + requireExactFinalAbort(binding, exactAbortBytes, existingAbort); + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new IllegalStateException( + "Durable final-abort evidence is not paired with terminal nonpublication state"); + } + requireFinalAbortSlotRelease(binding, commit); + return toFinalAbortReceipt(binding, existingAbort); + } + + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + if (slotRecord == null) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires the active Version application slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Only an unresolved owner-application workflow can record final-abort evidence"); + } + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A commit with a successful visibility fence cannot be finalized as nonpublication"); + } + + List ownerStates = lockAndReadOwnerStates(binding); + requireCompleteTerminalAbortVector(binding, ownerStates); + int inserted = + dsl.execute( + "INSERT INTO " + + FINAL_ABORT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, binding_json, abort_bytes) VALUES (?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + exactAbortBytes.clone()); + Record persisted = findFinalAbort(binding, true); + if (persisted == null) { + throw new IllegalStateException("Final-abort evidence insert returned no durable row"); + } + requireExactFinalAbort(binding, exactAbortBytes, persisted); + if (inserted == 0) { + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Concurrent final-abort evidence has no terminal nonpublication state"); + } + return toFinalAbortReceipt(binding, persisted); + } + + updateWorkflowState(binding, WorkflowState.FAILED_NONPUBLICATION); + return toFinalAbortReceipt(binding, persisted); + } + + private void requireFinalAbortSlotRelease(DraftCommitBinding binding, CommitRecord commit) { + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Only a terminal nonpublication commit can release by final-abort evidence"); + } + Record abort = findFinalAbort(binding, true); + if (abort == null) { + throw new DraftCommitStateConflictException( + "Failed nonpublication state lacks exact durable final-abort evidence"); + } + requireExactFinalAbort(binding, abort.get("abort_bytes", byte[].class), abort); + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A final-aborted Draft commit cannot own a successful visibility fence"); + } + requireCompleteTerminalAbortVector(binding, lockAndReadOwnerStates(binding)); + } + + private void requireCompleteTerminalAbortVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires every exact required owner result"); + } + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); + if (state.status() != OwnerStatus.APPLIED && state.status() != OwnerStatus.REJECTED) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires only exact terminal APPLIED or REJECTED owners"); + } + OwnerOutcome outcome = + state + .outcome() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence requires durable owner result bytes")); + requireOutcomeMatches(binding, outcome); + } + } + + private void updateWorkflowStateAfterOwnerOutcome( + DraftCommitBinding binding, OwnerOutcome outcome) { + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + commit = requireCommit(binding, true); + } + if (outcome.status() == OwnerStatus.UNKNOWN) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + return; + } + List states = lockAndReadOwnerStates(binding); + boolean hasApplied = states.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean hasRejected = states.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + boolean hasUnknown = states.stream().anyMatch(state -> state.status() == OwnerStatus.UNKNOWN); + if (hasUnknown || (hasApplied && hasRejected)) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + } + } + + private void updateWorkflowState(DraftCommitBinding binding, WorkflowState state) { + int updated = + dsl.execute( + "UPDATE " + + COMMIT_TABLE + + " SET workflow_state = ?, updated_at = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + + "AND workflow_state <> ?", + state.name(), + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + state.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException( + "Draft commit workflow state changed concurrently"); + } + } + + private CommitRecord requireExactCommitInTransaction(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + return requireCommit(binding, true); + } + + private CommitRecord requireCommit(DraftCommitBinding binding, boolean forUpdate) { + Objects.requireNonNull(binding, "binding"); + CommitRecord record = findCommit(binding, forUpdate); + if (record == null) { + throw new DraftCommitNotFoundException("Draft commit binding is missing"); + } + requireExactBinding(binding, record.binding()); + return record; + } + + private CommitRecord findCommit(DraftCommitBinding binding, boolean forUpdate) { + return findCommit(binding.target(), binding.requestId(), forUpdate); + } + + private CommitRecord findCommit( + DraftCommitBinding.TargetProof target, UUID requestId, boolean forUpdate) { + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?" + + suffix, + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId); + if (row == null) { + return null; + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!target.equals(binding.target()) + || !requestId.equals(binding.requestId()) + || !row.get("commit_id", UUID.class).equals(binding.commitId()) + || !row.get("base_commit_id", String.class).equals(binding.baseCommitId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(binding.target().gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(binding.target().gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(binding.target().sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class) + .equals(binding.target().sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class) + .equals(binding.target().sourceProvenanceKind())) { + throw new IllegalStateException( + "Draft commit indexed identity differs from its exact JSON binding"); + } + return new CommitRecord( + binding, + WorkflowState.valueOf(row.get("workflow_state", String.class)), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private CommitSnapshot snapshot(CommitRecord record) { + return new CommitSnapshot(record, readOwnerStates(record.binding(), false)); + } + + private List lockAndReadOwnerStates(DraftCommitBinding binding) { + return readOwnerStates(binding, true); + } + + private List readOwnerStates(DraftCommitBinding binding, boolean forUpdate) { + List states = + dsl + .fetch( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? ORDER BY owner" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()) + .stream() + .map(this::toOwnerState) + .toList(); + Map byOwner = new EnumMap<>(Owner.class); + for (OwnerState state : states) { + if (byOwner.put(state.owner(), state) != null) { + throw new IllegalStateException("Duplicate durable Draft owner status row"); + } + } + if (!byOwner.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new IllegalStateException( + "Durable Draft owner status set differs from its complete binding"); + } + return binding.requiredOwners().stream().map(byOwner::get).toList(); + } + + private OwnerState requireOwnerState(DraftCommitBinding binding, Owner owner, boolean forUpdate) { + Objects.requireNonNull(owner, "owner"); + if (!binding.requiredOwners().contains(owner)) { + throw new DraftCommitStateConflictException( + "Owner is not in this Draft commit's required set"); + } + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ?" + + suffix, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (row == null) { + throw new IllegalStateException("Required Draft owner status row is missing"); + } + return toOwnerState(row); + } + + private OwnerState toOwnerState(Record row) { + Owner owner = Owner.valueOf(row.get("owner", String.class)); + OwnerStatus status = OwnerStatus.valueOf(row.get("status", String.class)); + UUID resultCommitId = row.get("result_commit_id", UUID.class); + String digest = row.get("result_binding_digest", String.class); + String resultIdentity = row.get("result_identity", String.class); + byte[] resultBytes = row.get("result_bytes", byte[].class); + String appliedUnitsJson = row.get("applied_units_json", String.class); + OwnerOutcome outcome = null; + if (resultCommitId != null || digest != null || resultIdentity != null || resultBytes != null) { + if (resultCommitId == null || digest == null) { + throw new IllegalStateException("Draft owner result has incomplete commit identity"); + } + List epochs = + appliedUnitsJson == null ? List.of() : parseAppliedEpochs(appliedUnitsJson); + outcome = + new OwnerOutcome( + owner, status, resultCommitId, digest, resultIdentity, resultBytes, epochs); + } + return new OwnerState( + owner, + status, + Optional.ofNullable(outcome), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private List parseAppliedEpochs(String appliedUnitsJson) { + try { + List epochs = new ArrayList<>(); + for (tools.jackson.databind.JsonNode node : JSON.readTree(appliedUnitsJson)) { + epochs.add( + new AppliedEpoch( + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"), + requiredText(node, "resultingEpoch"))); + } + if (!canonicalJson(epochs.stream().map(this::appliedEpochJson).toList()) + .equals(appliedUnitsJson)) { + throw new IllegalStateException("Persisted Draft owner epoch vector is not canonical"); + } + return List.copyOf(epochs); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Draft owner epoch vector is corrupt", exception); + } + } + + private Record findSlot(DraftCommitBinding.TargetProof target, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + } + + private ApplicationSlot toApplicationSlot(Record row) { + return new ApplicationSlot( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("request_id", UUID.class), + row.get("commit_id", UUID.class), + row.get("claimed_at", OffsetDateTime.class)); + } + + private void requireActiveSlot(DraftCommitBinding binding) { + Record row = findSlot(binding.target(), true); + if (row == null) { + throw new DraftCommitStateConflictException( + "Owner dispatch requires the durable Version slot"); + } + requireSameSlot(binding, toApplicationSlot(row)); + } + + private static boolean isSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + return slot.canonicalTenantId().equals(binding.target().canonicalTenantId()) + && slot.canonicalVersionId().equals(binding.target().canonicalVersionId()) + && slot.requestId().equals(binding.requestId()) + && slot.commitId().equals(binding.commitId()); + } + + private static void requireSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + if (!isSameSlot(binding, slot)) { + throw new DraftCommitStateConflictException( + "Another exact Draft commit owns the Version application slot"); + } + } + + private VisibilityFence findVisibilityFence(DraftCommitBinding binding, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + return row == null + ? null + : toVisibilityFence(binding.target(), binding.requestId(), binding.commitId(), row); + } + + private Record findFinalAbort(DraftCommitBinding binding, boolean forUpdate) { + return dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes, created_at FROM " + + FINAL_ABORT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + } + + private void requireExactFinalAbort( + DraftCommitBinding binding, byte[] expectedAbortBytes, Record row) { + if (!binding.digest().equals(row.get("input_digest", String.class)) + || !binding.canonicalJson().equals(row.get("binding_json", String.class)) + || !Arrays.equals(expectedAbortBytes, row.get("abort_bytes", byte[].class))) { + throw new DraftCommitIdentityConflictException( + "Final-abort identity was reused with changed binding or exact evidence bytes"); + } + } + + private FinalAbortReceipt toFinalAbortReceipt(DraftCommitBinding binding, Record row) { + requireExactFinalAbort(binding, row.get("abort_bytes", byte[].class), row); + return new FinalAbortReceipt( + binding, row.get("abort_bytes", byte[].class), row.get("created_at", OffsetDateTime.class)); + } + + private VisibilityFence toVisibilityFence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, Record row) { + return new VisibilityFence( + target, + requestId, + commitId, + row.get("input_digest", String.class), + row.get("result_vector_json", String.class), + row.get("created_at", OffsetDateTime.class)); + } + + private String exactAppliedResultVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException("Complete Draft owner result vector is required"); + } + List> resultVector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Required Draft owner result is missing")); + OwnerOutcome outcome = state.outcome().orElse(null); + if (state.status() != OwnerStatus.APPLIED || outcome == null) { + throw new DraftCommitStateConflictException( + "Draft visibility cannot advance before every required owner is exactly APPLIED"); + } + requireOutcomeMatches(binding, outcome); + List expected = binding.affectedUnits(owner); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result does not prove the complete bound affected tuple set"); + } + resultVector.add(ownerResultJson(outcome)); + } + return canonicalJson(resultVector); + } + + private Map ownerResultJson(OwnerOutcome outcome) { + Map item = new LinkedHashMap<>(); + item.put("owner", outcome.owner().name()); + item.put("status", outcome.status().name()); + item.put("commitId", outcome.commitId().toString()); + item.put("bindingDigest", outcome.bindingDigest()); + item.put("resultIdentity", outcome.resultIdentity()); + item.put( + "resultBytesBase64", + outcome.resultBytes() == null + ? "" + : Base64.getEncoder().encodeToString(outcome.resultBytes())); + item.put( + "appliedEpochs", outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + return item; + } + + private Map appliedEpochJson(AppliedEpoch epoch) { + Map item = new LinkedHashMap<>(); + item.put("aggregateType", epoch.aggregateType()); + item.put("aggregateId", epoch.aggregateId()); + item.put("scopeType", epoch.scopeType()); + item.put("scopeId", epoch.scopeId()); + item.put("expectedEpoch", epoch.expectedEpoch()); + item.put("resultingEpoch", epoch.resultingEpoch()); + return item; + } + + private void requireOutcomeMatches(DraftCommitBinding binding, OwnerOutcome outcome) { + if (!binding.requiredOwners().contains(outcome.owner()) + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest())) { + throw new DraftCommitIdentityConflictException( + "Draft owner outcome is not bound to this exact commit and full input digest"); + } + if (outcome.status() == OwnerStatus.APPLIED) { + List expected = binding.affectedUnits(outcome.owner()); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result omitted a declared aggregate/scope epoch tuple"); + } + for (AppliedEpoch actualEpoch : outcome.appliedEpochs()) { + if (new BigInteger(actualEpoch.resultingEpoch()) + .compareTo(new BigInteger(actualEpoch.expectedEpoch())) + <= 0) { + throw new DraftCommitStateConflictException( + "Draft owner result does not exactly advance every declared tuple"); + } + } + } else if (!outcome.appliedEpochs().isEmpty()) { + throw new DraftCommitStateConflictException( + "Only an APPLIED owner result may report advanced aggregate/scope epochs"); + } + } + + private boolean hasExpectedTuples(List expected, List actual) { + if (expected.size() != actual.size()) { + return false; + } + for (int index = 0; index < expected.size(); index++) { + if (!actual.get(index).matchesExpectedTuple(expected.get(index))) { + return false; + } + } + return true; + } + + private void requireExactBinding(DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitIdentityConflictException( + "Draft request or commit identity was reused with changed complete binding data"); + } + } + + /** + * Locks and proves one canonical Game Design Version before any Draft commit/application lock. + */ + LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) { + requireWritableReadCommittedTransaction(); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + dsl.fetchOne( + "SELECT v.id AS version_row_id, v.tenant_id AS version_tenant_key, " + + "v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, " + + "v.identity_source_provenance_kind, v.version_state, v.version_state_epoch, " + + "v.is_script_only, v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') " + + "FOR UPDATE OF v", + canonicalTenantId, + canonicalVersionId); + if (row == null) { + throw new DraftCommitNotFoundException( + "Exact canonical Version and immutable Game source provenance were not found"); + } + Long stateEpoch = row.get("version_state_epoch", Long.class); + if (stateEpoch == null || stateEpoch <= 0) { + throw new DraftCommitStateConflictException( + "Canonical Version lacks a positive persisted version-state epoch"); + } + TargetProof target = + new TargetProof( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("version_row_id", Long.class), + row.get("version_tenant_key", String.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class)); + return new LockedVersion( + target, + row.get("version_state", String.class), + stateEpoch, + row.get("is_script_only", Boolean.class), + row.get("script_patch_version", String.class), + row.get("base_version_id", Long.class)); + } + + private LockedVersion lockVersionTarget(TargetProof expected) { + Objects.requireNonNull(expected, "expected"); + LockedVersion locked = + lockVersionTarget(expected.canonicalTenantId(), expected.canonicalVersionId()); + if (!expected.equals(locked.target())) { + throw new DraftCommitIdentityConflictException( + "Draft binding source proof differs from its locked canonical Version"); + } + return locked; + } + + private static void requireDraftVersion(LockedVersion version) { + if (!"DRAFT".equals(version.versionState())) { + throw new DraftCommitStateConflictException( + "Owner application requires the exact Version to remain DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + Record selection = + dsl.fetchOne( + "SELECT publish_request_id FROM " + + PUBLISH_SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selection != null) { + throw new DraftCommitStateConflictException( + "Authored Draft publication reservation prevents later owner application"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Draft coordinator mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + private static void requireTargetAndRequest( + DraftCommitBinding.TargetProof target, UUID requestId) { + requireTarget(target); + requireNonNil(requestId, "requestId"); + } + + private static void requireTarget(DraftCommitBinding.TargetProof target) { + Objects.requireNonNull(target, "target"); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static OffsetDateTime now() { + return OffsetDateTime.now(ZoneOffset.UTC); + } + + private static boolean isUniqueConstraintViolation(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState())) { + return true; + } + current = current.getCause(); + } + return false; + } + + private String canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return new String(canonical, StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft owner result evidence could not be canonicalized", exception); + } + } + + private static String requiredText(tools.jackson.databind.JsonNode node, String field) { + tools.jackson.databind.JsonNode value = node == null ? null : node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Persisted Draft owner epoch field is missing: " + field); + } + return value.textValue(); + } + + private record CommitRecord( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) {} + + record LockedVersion( + DraftCommitBinding.TargetProof target, + String versionState, + long versionStateEpoch, + boolean scriptOnly, + String scriptPatchVersion, + Long baseVersionId) {} + + public record PublicationEvidence(DraftCommitBinding binding, VisibilityFence visibilityFence) { + public PublicationEvidence { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + } + } + + public enum WorkflowState { + QUEUED, + APPLYING, + RECONCILIATION_REQUIRED, + SYNCHRONIZED, + REJECTED, + FAILED_NONPUBLICATION + } + + public enum OwnerStatus { + NOT_ATTEMPTED, + IN_PROGRESS, + APPLIED, + REJECTED, + UNKNOWN + } + + public record OwnerState( + Owner owner, + OwnerStatus status, + Optional outcome, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + public OwnerState { + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(status, "status"); + outcome = Objects.requireNonNull(outcome, "outcome"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + if ((status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) + != outcome.isEmpty()) { + throw new IllegalArgumentException("Draft owner status/result shape is inconsistent"); + } + if (outcome.isPresent() + && (outcome.orElseThrow().owner() != owner || outcome.orElseThrow().status() != status)) { + throw new IllegalArgumentException( + "Draft owner result identity differs from its status row"); + } + } + } + + public record CommitSnapshot( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt, + Map ownerStates) { + private CommitSnapshot(CommitRecord record, List states) { + this( + record.binding(), + record.workflowState(), + record.createdAt(), + record.updatedAt(), + ownerStateMap(states)); + } + + public CommitSnapshot { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(workflowState, "workflowState"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + ownerStates = Map.copyOf(ownerStates); + } + + private static Map ownerStateMap(List states) { + Map result = new EnumMap<>(Owner.class); + states.forEach(state -> result.put(state.owner(), state)); + return result; + } + } + + public record ApplicationSlot( + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID requestId, + UUID commitId, + OffsetDateTime claimedAt) { + public ApplicationSlot { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(claimedAt, "claimedAt"); + } + } + + public record VisibilityFence( + DraftCommitBinding.TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) { + public VisibilityFence { + Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(inputDigest, "inputDigest"); + Objects.requireNonNull(resultVectorJson, "resultVectorJson"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } + + /** Exact immutable producer evidence that a commit is fenced from any later GD commit. */ + public record FinalAbortReceipt( + DraftCommitBinding binding, byte[] abortBytes, OffsetDateTime createdAt) { + public FinalAbortReceipt { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(abortBytes, "abortBytes"); + if (abortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + abortBytes = abortBytes.clone(); + Objects.requireNonNull(createdAt, "createdAt"); + } + + @Override + public byte[] abortBytes() { + return abortBytes.clone(); + } + } + + public record AppliedEpoch( + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch, + String resultingEpoch) { + public AppliedEpoch { + requireResultText(aggregateType, "aggregateType"); + requireResultText(aggregateId, "aggregateId"); + requireResultText(scopeType, "scopeType"); + requireResultText(scopeId, "scopeId"); + requireDecimal(expectedEpoch, "expectedEpoch"); + requireDecimal(resultingEpoch, "resultingEpoch"); + } + + private boolean matchesExpectedTuple(AffectedUnit expected) { + return aggregateType.equals(expected.aggregateType()) + && aggregateId.equals(expected.aggregateId()) + && scopeType.equals(expected.scopeType()) + && scopeId.equals(expected.scopeId()) + && expectedEpoch.equals(expected.expectedEpoch()); + } + } + + /** + * Internal handoff token for the future coordinator after every authenticated owner producer has + * been validated. Its package-private constructor deliberately leaves this storage slice unwired; + * a repository can persist a fence only when a same-package coordinator supplies the exact + * durable owner outcomes it has independently verified. + */ + public static final class CoordinatorProof { + private final DraftCommitBinding binding; + private final List outcomes; + + CoordinatorProof(DraftCommitBinding binding, List outcomes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.outcomes = List.copyOf(outcomes); + } + + private boolean matches(DraftCommitBinding candidate) { + return binding.equals(candidate); + } + + private void requireSameOutcomes(List states) { + Map verified = new EnumMap<>(Owner.class); + for (OwnerOutcome outcome : outcomes) { + if (outcome.status() != OwnerStatus.APPLIED + || verified.put(outcome.owner(), outcome) != null) { + throw new DraftCommitStateConflictException( + "Coordinator proof must contain one exact APPLIED result per required owner"); + } + } + if (!verified.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new DraftCommitStateConflictException( + "Coordinator proof omits or adds a required Draft owner"); + } + for (OwnerState state : states) { + OwnerOutcome outcome = verified.get(state.owner()); + if (state.status() != OwnerStatus.APPLIED + || outcome == null + || state.outcome().isEmpty() + || !state.outcome().orElseThrow().equals(outcome)) { + throw new DraftCommitStateConflictException( + "Coordinator proof differs from the exact durable owner result row"); + } + } + } + } + + /** Immutable copy of an owner's full terminal or uncertain result evidence. */ + public static final class OwnerOutcome { + private final Owner owner; + private final OwnerStatus status; + private final UUID commitId; + private final String bindingDigest; + private final String resultIdentity; + private final byte[] resultBytes; + private final List appliedEpochs; + + public OwnerOutcome( + Owner owner, + OwnerStatus status, + UUID commitId, + String bindingDigest, + String resultIdentity, + byte[] resultBytes, + List appliedEpochs) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.status = Objects.requireNonNull(status, "status"); + if (status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) { + throw new IllegalArgumentException( + "OwnerOutcome must carry an observed owner result state"); + } + requireNonNil(commitId, "commitId"); + this.commitId = commitId; + this.bindingDigest = Objects.requireNonNull(bindingDigest, "bindingDigest"); + if (!bindingDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("bindingDigest must be a canonical SHA-256 digest"); + } + if ((resultIdentity == null) != (resultBytes == null)) { + throw new IllegalArgumentException( + "Owner result identity and exact result bytes must be paired"); + } + if (status == OwnerStatus.APPLIED || status == OwnerStatus.REJECTED) { + requireResultText(resultIdentity, "resultIdentity"); + } else if (resultIdentity != null) { + requireResultText(resultIdentity, "resultIdentity"); + } + this.resultIdentity = resultIdentity; + this.resultBytes = resultBytes == null ? null : resultBytes.clone(); + Objects.requireNonNull(appliedEpochs, "appliedEpochs"); + List epochCopy = new ArrayList<>(appliedEpochs); + epochCopy.sort(APPLIED_EPOCH_ORDER); + if (!epochCopy.equals(appliedEpochs)) { + throw new IllegalArgumentException("Applied owner epoch tuples must be in canonical order"); + } + if ((status == OwnerStatus.APPLIED) != !epochCopy.isEmpty()) { + throw new IllegalArgumentException("APPLIED result must contain its complete tuple vector"); + } + this.appliedEpochs = List.copyOf(epochCopy); + } + + public Owner owner() { + return owner; + } + + public OwnerStatus status() { + return status; + } + + public UUID commitId() { + return commitId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public String resultIdentity() { + return resultIdentity; + } + + public byte[] resultBytes() { + return resultBytes == null ? null : resultBytes.clone(); + } + + public List appliedEpochs() { + return appliedEpochs; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof OwnerOutcome result + && owner == result.owner + && status == result.status + && commitId.equals(result.commitId) + && bindingDigest.equals(result.bindingDigest) + && Objects.equals(resultIdentity, result.resultIdentity) + && Arrays.equals(resultBytes, result.resultBytes) + && appliedEpochs.equals(result.appliedEpochs)); + } + + @Override + public int hashCode() { + return Objects.hash( + owner, + status, + commitId, + bindingDigest, + resultIdentity, + Arrays.hashCode(resultBytes), + appliedEpochs); + } + } + + private static void requireDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + private static void requireResultText(String value, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank exact text"); + } + } + + public static class DraftCommitIdentityConflictException extends IllegalStateException { + public DraftCommitIdentityConflictException(String message) { + super(message); + } + + public DraftCommitIdentityConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class DraftCommitStateConflictException extends IllegalStateException { + public DraftCommitStateConflictException(String message) { + super(message); + } + } + + public static final class DraftCommitNotFoundException extends IllegalStateException { + public DraftCommitNotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql new file mode 100644 index 0000000000..c338bca9eb --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql @@ -0,0 +1,865 @@ +CREATE TABLE game_design_draft_commit ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + workflow_state VARCHAR(32) NOT NULL DEFAULT 'QUEUED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ), + CONSTRAINT uq_gd_draft_commit_target_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + commit_id + ), + CONSTRAINT uq_gd_draft_commit_exact_identity UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_canonical_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_draft_commit_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_draft_commit_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_binding_json CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_state CHECK ( + workflow_state IN ( + 'QUEUED', 'APPLYING', 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', + 'REJECTED', 'FAILED_NONPUBLICATION' + ) + ) +); + +CREATE TABLE game_design_draft_commit_owner_result ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL, + status VARCHAR(24) NOT NULL, + result_commit_id UUID, + result_binding_digest VARCHAR(71), + result_identity VARCHAR(512), + result_bytes BYTEA, + applied_units_json TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_owner_result PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + owner + ), + CONSTRAINT fk_gd_draft_commit_owner_result_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_owner CHECK ( + owner IN ( + 'WORLD_MANAGEMENT', + 'ENTITY_MANAGEMENT', + 'GAME_LOGIC', + 'AUTOMATION_SCRIPTING', + 'GAME_DESIGN_CONTROL_PLANE' + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_status CHECK ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS', 'APPLIED', 'REJECTED', 'UNKNOWN') + ), + CONSTRAINT chk_gd_draft_commit_owner_result_shape CHECK ( + ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS') + AND result_commit_id IS NULL + AND result_binding_digest IS NULL + AND result_identity IS NULL + AND result_bytes IS NULL + AND applied_units_json IS NULL + ) + OR + ( + status = 'UNKNOWN' + AND ( + (result_identity IS NULL AND result_bytes IS NULL) + OR (result_identity IS NOT NULL AND result_bytes IS NOT NULL) + ) + AND ( + (result_commit_id IS NULL AND result_binding_digest IS NULL AND applied_units_json IS NULL) + OR (result_commit_id IS NOT NULL AND result_binding_digest IS NOT NULL) + ) + ) + OR + ( + status IN ('APPLIED', 'REJECTED') + AND result_commit_id IS NOT NULL + AND result_binding_digest IS NOT NULL + AND result_identity IS NOT NULL + AND result_bytes IS NOT NULL + AND applied_units_json IS NOT NULL + AND jsonb_typeof(applied_units_json::jsonb) = 'array' + AND (status <> 'REJECTED' OR applied_units_json::jsonb = '[]'::jsonb) + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_result_digest CHECK ( + result_binding_digest IS NULL OR result_binding_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_owner_result_identity CHECK ( + result_identity IS NULL OR ( + char_length(result_identity) BETWEEN 1 AND 512 + AND result_identity !~ '^[[:space:]]*$' + ) + ) +); + +CREATE TABLE game_design_draft_commit_visibility_fence ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + result_vector_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility_fence PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_visibility_vector CHECK ( + jsonb_typeof(result_vector_json::jsonb) = 'array' + ) +); + +CREATE TABLE game_design_draft_commit_visibility ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_pointer_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE game_design_draft_commit_application_slot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_application_slot PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_application_slot_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT +); + +CREATE TABLE game_design_draft_commit_final_abort ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + abort_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_final_abort PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_final_abort_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_final_abort_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_binding CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_bytes CHECK (octet_length(abort_bytes) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_commit_has_exact_terminal_abort_vector( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_count INTEGER; + actual_count INTEGER; +BEGIN + SELECT input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request + AND commit_id = target_commit; + IF NOT FOUND THEN + RETURN FALSE; + END IF; + IF jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' + OR jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners') = 0 THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + SELECT count(*) INTO actual_count + FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request; + IF actual_count <> expected_count THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = target_tenant + AND outcome.canonical_version_id = target_version + AND outcome.request_id = target_request + AND outcome.owner = required.owner + WHERE outcome.owner IS NULL + OR outcome.status NOT IN ('APPLIED', 'REJECTED') + OR outcome.result_commit_id IS DISTINCT FROM target_commit + OR outcome.result_binding_digest IS DISTINCT FROM parent_record.input_digest + OR outcome.result_identity IS NULL + OR outcome.result_bytes IS NULL + OR outcome.applied_units_json IS NULL + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_commit_final_abort() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence is immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json, workflow_state + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.binding_json + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Final-abort evidence must bind the exact active Draft commit' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'A successful Draft visibility fence cannot be final-aborted' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT gd_draft_commit_has_exact_terminal_abort_vector( + NEW.canonical_tenant_id, + NEW.canonical_version_id, + NEW.request_id, + NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-abort evidence requires every exact owner result to be terminal' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_final_abort + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_final_abort(); + +CREATE FUNCTION reject_gd_draft_commit_final_abort_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_final_abort) THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_final_abort + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_final_abort_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_binding() RETURNS trigger AS $$ +DECLARE + version_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft commit bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.game_design_version_row_id IS DISTINCT FROM OLD.game_design_version_row_id + OR NEW.game_design_version_tenant_key IS DISTINCT FROM OLD.game_design_version_tenant_key + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.base_commit_id IS DISTINCT FROM OLD.base_commit_id + OR NEW.input_digest IS DISTINCT FROM OLD.input_digest + OR NEW.binding_json IS DISTINCT FROM OLD.binding_json + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft commit binding identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.workflow_state IS DISTINCT FROM OLD.workflow_state THEN + IF OLD.workflow_state IN ('SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION') + OR NOT ( + (OLD.workflow_state = 'QUEUED' + AND NEW.workflow_state = 'APPLYING') + OR (OLD.workflow_state = 'APPLYING' + AND NEW.workflow_state IN ( + 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', 'REJECTED', + 'FAILED_NONPUBLICATION' + )) + OR (OLD.workflow_state = 'RECONCILIATION_REQUIRED' + AND NEW.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + )) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft commit workflow transition' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'An unchanged Draft commit workflow state is not rewritten' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'REJECTED' + AND ( + EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) + OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) + ) THEN + RAISE EXCEPTION 'Unresolved or applied Draft owner outcomes cannot be finalized REJECTED' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'FAILED_NONPUBLICATION' + AND ( + NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = OLD.input_digest + AND abort.binding_json = OLD.binding_json + ) + OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) + ) THEN + RAISE EXCEPTION 'Failed nonpublication requires exact final-abort evidence and no visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.binding_json::jsonb ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.binding_json::jsonb ->> 'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id + OR NEW.binding_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its indexed identity' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + ) INTO version_matches; + IF NOT version_matches THEN + RAISE EXCEPTION 'Draft commit target lacks exact canonical Game Design Version source proof' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_binding(); + +CREATE FUNCTION reject_gd_draft_commit_binding_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit) THEN + RAISE EXCEPTION 'Game Design Draft commit bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_binding_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_owner_result() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft owner results are retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design Draft owner result has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF NOT ((parent_record.binding_json::jsonb -> 'requiredOwners') ? NEW.owner) THEN + RAISE EXCEPTION 'Game Design Draft owner result is outside the bound required owner set' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'NOT_ATTEMPTED' + OR NEW.result_commit_id IS NOT NULL + OR NEW.result_binding_digest IS NOT NULL + OR NEW.result_identity IS NOT NULL + OR NEW.result_bytes IS NOT NULL + OR NEW.applied_units_json IS NOT NULL THEN + RAISE EXCEPTION 'Draft commit owner result must begin NOT_ATTEMPTED without evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.owner IS DISTINCT FROM OLD.owner + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft owner result identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status = OLD.status THEN + IF NEW.result_commit_id IS DISTINCT FROM OLD.result_commit_id + OR NEW.result_binding_digest IS DISTINCT FROM OLD.result_binding_digest + OR NEW.result_identity IS DISTINCT FROM OLD.result_identity + OR NEW.result_bytes IS DISTINCT FROM OLD.result_bytes + OR NEW.applied_units_json IS DISTINCT FROM OLD.applied_units_json + OR NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'Exact Draft owner result retries do not rewrite persisted evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NOT ( + (OLD.status = 'NOT_ATTEMPTED' AND NEW.status = 'IN_PROGRESS') + OR (OLD.status = 'IN_PROGRESS' AND NEW.status IN ('APPLIED', 'REJECTED', 'UNKNOWN')) + OR (OLD.status = 'UNKNOWN' AND NEW.status IN ('APPLIED', 'REJECTED')) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft owner result transition' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status IN ('APPLIED', 'REJECTED') + AND (NEW.result_commit_id IS DISTINCT FROM parent_record.commit_id + OR NEW.result_binding_digest IS DISTINCT FROM parent_record.input_digest) THEN + RAISE EXCEPTION 'Game Design Draft owner result does not match its exact commit binding' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_owner_result + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_owner_result + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_owner_result(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_fence() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft visibility fences are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, workflow_state, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.commit_id IS DISTINCT FROM NEW.commit_id + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Draft visibility fence lacks a matching nonterminal commit binding' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-aborted Draft commits cannot gain a visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Draft visibility fence requires every exact required owner to be APPLIED' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_visibility_fence + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_fence(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_fence_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence) THEN + RAISE EXCEPTION 'Game Design Draft visibility fences cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_visibility_fence + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_visibility_fence_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_pointer() RETURNS trigger AS $$ +DECLARE + fence_digest VARCHAR(71); + workflow_state VARCHAR(32); +BEGIN + SELECT f.input_digest, c.workflow_state INTO fence_digest, workflow_state + FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = f.canonical_tenant_id + AND c.canonical_version_id = f.canonical_version_id + AND c.request_id = f.request_id + AND c.commit_id = f.commit_id + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id; + IF NOT FOUND OR fence_digest IS DISTINCT FROM NEW.input_digest + OR workflow_state = 'FAILED_NONPUBLICATION' + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Draft visibility pointer must name its exact durable fence' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer + BEFORE INSERT OR UPDATE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_pointer(); + +CREATE FUNCTION enforce_gd_draft_commit_application_slot() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + SELECT workflow_state, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = OLD.canonical_tenant_id + AND canonical_version_id = OLD.canonical_version_id + AND request_id = OLD.request_id + AND commit_id = OLD.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Draft application slot has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.workflow_state = 'SYNCHRONIZED' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + AND f.input_digest = parent_record.input_digest + ) OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = OLD.canonical_tenant_id + AND outcome.canonical_version_id = OLD.canonical_version_id + AND outcome.request_id = OLD.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Synchronized Draft application slot requires its exact complete fence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'REJECTED' THEN + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) THEN + RAISE EXCEPTION 'Rejected Draft application slot cannot hide unresolved or applied owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'FAILED_NONPUBLICATION' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = parent_record.input_digest + AND abort.binding_json = parent_record.binding_json + ) OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) THEN + RAISE EXCEPTION 'Failed nonpublication slot release requires exact abort proof and terminal owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Draft application slot cannot be released before a terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design Draft application slot identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT workflow_state INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND OR parent_record.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + ) THEN + RAISE EXCEPTION 'Draft application slot requires an exact nonterminal commit' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_application_slot + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_application_slot(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql new file mode 100644 index 0000000000..6e5f48645e --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql @@ -0,0 +1,265 @@ +CREATE TABLE game_design_authored_draft_publish_selection ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + publish_request_id VARCHAR(1024) NOT NULL, + version_state_epoch BIGINT NOT NULL, + selected_commit_request_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + selected_commit_digest VARCHAR(71) NOT NULL, + selection_digest VARCHAR(71) NOT NULL, + selection_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_authored_draft_publish_selection PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT uq_gd_authored_draft_publish_selection_request UNIQUE ( + canonical_tenant_id, + canonical_version_id, + publish_request_id + ), + CONSTRAINT fk_gd_authored_draft_publish_selection_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_authored_draft_publish_selection_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + AND char_length(publish_request_id) BETWEEN 1 AND 1024 + AND publish_request_id !~ '^[[:space:]]*$' + AND publish_request_id !~ ':' + AND version_state_epoch > 0 + AND selected_commit_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_digests CHECK ( + selected_commit_digest ~ '^sha256:[0-9a-f]{64}$' + AND selection_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_json CHECK ( + jsonb_typeof(selection_json::jsonb) = 'object' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_draft_publish_selection() RETURNS trigger AS $$ +DECLARE + version_record RECORD; + commit_record RECORD; + current_fence RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Authored Draft publication selections are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'publishRequestId' + IS DISTINCT FROM NEW.publish_request_id + OR NEW.selection_json::jsonb -> 'intent' ->> 'expectedVersionStateEpoch' + IS DISTINCT FROM NEW.version_state_epoch::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitRequestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its complete caller intent' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'target' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_state, v.version_state_epoch, v.is_script_only, + v.script_patch_version, v.base_version_id + INTO version_record + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND v.version_state = 'DRAFT' + AND v.version_state_epoch = NEW.version_state_epoch + AND v.version_state_epoch > 0 + AND v.is_script_only = FALSE + AND v.script_patch_version IS NULL + AND v.base_version_id IS NULL + FOR UPDATE OF v; + IF NOT FOUND THEN + RAISE EXCEPTION 'Authored Draft publication selection lacks an exact current full Draft Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Active or unresolved owner application prevents Draft publication selection' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT c.commit_id, c.input_digest, c.binding_json, c.workflow_state + INTO commit_record + FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.selected_commit_request_id + AND c.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR commit_record.workflow_state <> 'SYNCHRONIZED' + OR commit_record.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitDigest' + IS DISTINCT FROM commit_record.input_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitBindingJson' + IS DISTINCT FROM commit_record.binding_json THEN + RAISE EXCEPTION 'Selected authored Draft commit is missing or differs from exact durable binding' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'requestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'commitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'inputDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from exact synchronized fence identity' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT f.input_digest, f.result_vector_json + INTO current_fence + FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.selected_commit_request_id + AND f.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR current_fence.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'resultVectorJson' + IS DISTINCT FROM current_fence.result_vector_json THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from the exact immutable result fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.request_id = NEW.selected_commit_request_id + AND v.commit_id = NEW.selected_commit_id + AND v.input_digest = NEW.selected_commit_digest + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit is stale relative to current synchronized visibility' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(commit_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.selected_commit_request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit lacks every required APPLIED owner outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_authored_draft_publish_selection + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_draft_publish_selection + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_authored_draft_publish_selection(); + +CREATE FUNCTION reject_gd_draft_application_during_authored_publication() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Authored Draft publication reservation prevents later owner application' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_application_authored_publication_interlock + BEFORE INSERT ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION reject_gd_draft_application_during_authored_publication(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java new file mode 100644 index 0000000000..96fd0ec62b --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java @@ -0,0 +1,600 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.ApplicationSlot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitNotFoundException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitStateConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.WorkflowState; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AuthoredDraftPublishSelectionRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String LARGE_EPOCH = "9007199254740993"; + private static final String WORLD_EPOCH = "900719925474099312345678901234567890"; + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static Fixture fixture; + + @BeforeAll + static void setUpSchema() { + fixture = createFixture(); + } + + @Test + void reusesExistingAuthoredVersionAndExactReplayIgnoresLaterServerState() { + VersionFixture version = fixture.newVersion(Long.parseLong(LARGE_EPOCH)); + DraftCommitBinding binding = binding(version.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(binding); + long versionCountBeforeSelection = fixture.versionCount(); + PublishIntent intent = intent(version, binding, "publication notes"); + + SelectionSnapshot first = inTransaction(() -> fixture.selections().reserve(intent)); + inTransaction( + () -> { + int updated = + fixture + .dsl() + .execute( + "UPDATE version SET version_state = ?, version_state_epoch = version_state_epoch + 1 " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + VersionLifecycleState.PUBLISHED.name(), + version.target().canonicalTenantId(), + version.target().canonicalVersionId()); + assertThat(updated).isEqualTo(1); + return null; + }); + SelectionSnapshot exactReplay = inTransaction(() -> fixture.selections().reserve(intent)); + + assertThat(first.selection().target().gameDesignVersionRowId()).isEqualTo(version.rowId()); + assertThat(exactReplay.selection().canonicalBytes()) + .containsExactly(first.selection().canonicalBytes()); + assertThat(exactReplay.selection().digest()).isEqualTo(first.selection().digest()); + assertThat(exactReplay.createdAt()).isEqualTo(first.createdAt()); + assertThat(fixture.versionCount()).isEqualTo(versionCountBeforeSelection); + assertThat( + fixture + .selections() + .read( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + intent.publishRequestId())) + .contains(exactReplay); + + assertChangedIntentConflicts(intent, binding); + assertThat( + fixture + .selections() + .read( + fixture.newVersion(1L).target().canonicalTenantId(), + version.target().canonicalVersionId(), + intent.publishRequestId())) + .isEmpty(); + } + + @Test + void rejectsPublishedScriptOnlyUnmappedPartialStaleAndMismatchedTargets() { + VersionFixture published = fixture.newVersion(1L); + inTransaction( + () -> { + fixture + .dsl() + .execute( + "UPDATE version SET version_state = ? WHERE id = ?", + VersionLifecycleState.PUBLISHED.name(), + published.rowId()); + return null; + }); + assertThatThrownBy( + () -> inTransaction(() -> fixture.selections().reserve(emptyIntent(published)))) + .isInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("DRAFT"); + + VersionFixture full = fixture.newVersion(1L); + VersionFixture scriptOnly = fixture.newScriptOnlyVersion(full); + assertThatThrownBy( + () -> inTransaction(() -> fixture.selections().reserve(emptyIntent(scriptOnly)))) + .isInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("non-script-only"); + + PublishIntent unmapped = + new PublishIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "unmapped-request", + "1", + "notes", + UUID.randomUUID(), + UUID.randomUUID(), + sha256("unmapped")); + assertThatThrownBy(() -> inTransaction(() -> fixture.selections().reserve(unmapped))) + .isInstanceOf(DraftCommitNotFoundException.class); + + DraftCommitBinding partial = binding(full.target(), UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(partial)); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.selections().reserve(intent(full, partial, "partial notes")))) + .isInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("synchronized"); + + VersionFixture staleVersion = fixture.newVersion(1L); + DraftCommitBinding oldCommit = + binding(staleVersion.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(oldCommit); + DraftCommitBinding currentCommit = + binding(staleVersion.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(currentCommit); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.selections().reserve(intent(staleVersion, oldCommit, "stale")))) + .isInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("stale"); + + VersionFixture mismatchedVersion = fixture.newVersion(1L); + DraftCommitBinding actual = + binding(mismatchedVersion.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(actual); + PublishIntent mismatched = + new PublishIntent( + mismatchedVersion.target().canonicalTenantId(), + mismatchedVersion.target().canonicalVersionId(), + "mismatched-request", + "1", + "notes", + actual.requestId(), + UUID.randomUUID(), + actual.digest()); + assertThatThrownBy(() -> inTransaction(() -> fixture.selections().reserve(mismatched))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void failedReservationTransactionLeavesNoSelection() { + VersionFixture version = fixture.newVersion(1L); + DraftCommitBinding binding = binding(version.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(binding); + PublishIntent intent = intent(version, binding, "rollback notes"); + + fixture + .ownerTransaction() + .executeWithoutResult( + status -> { + fixture.selections().reserve(intent); + status.setRollbackOnly(); + }); + + assertThat( + fixture + .selections() + .read( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + intent.publishRequestId())) + .isEmpty(); + } + + @Test + void versionRowLockSerializesSelectionAgainstApplicationSlotClaim() throws Exception { + VersionFixture version = fixture.newVersion(1L); + DraftCommitBinding selectedCommit = + binding(version.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(selectedCommit); + DraftCommitBinding queuedCommit = + binding(version.target(), UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(queuedCommit)); + PublishIntent intent = intent(version, selectedCommit, "race notes"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future selectionWon = + executor.submit( + () -> { + ready.countDown(); + await(start); + try { + inTransaction(() -> fixture.selections().reserve(intent)); + return true; + } catch (DraftCommitStateConflictException expected) { + return false; + } + }); + Future applicationWon = + executor.submit( + () -> { + ready.countDown(); + await(start); + try { + inTransaction(() -> fixture.coordinator().claimApplicationSlot(queuedCommit)); + return true; + } catch (DraftCommitStateConflictException expected) { + return false; + } + }); + await(ready); + start.countDown(); + boolean selected = selectionWon.get(20, TimeUnit.SECONDS); + boolean applicationClaimed = applicationWon.get(20, TimeUnit.SECONDS); + + assertThat(selected).isNotEqualTo(applicationClaimed); + assertThat( + fixture.coordinator().readVisibilityFence(version.target()).orElseThrow().commitId()) + .isEqualTo(selectedCommit.commitId()); + if (selected) { + assertThat( + fixture + .selections() + .read( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + intent.publishRequestId())) + .isPresent(); + assertThat(fixture.coordinator().readApplicationSlot(version.target())).isEmpty(); + } else { + Optional slot = + fixture.coordinator().readApplicationSlot(version.target()); + assertThat(slot).isPresent(); + assertThat(slot.orElseThrow().commitId()).isEqualTo(queuedCommit.commitId()); + assertThat( + fixture + .selections() + .read( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + intent.publishRequestId())) + .isEmpty(); + } + assertThat( + fixture + .coordinator() + .read(version.target(), queuedCommit.requestId()) + .orElseThrow() + .workflowState()) + .isEqualTo(WorkflowState.QUEUED); + } finally { + executor.shutdownNow(); + } + } + + private static void assertChangedIntentConflicts( + PublishIntent intent, DraftCommitBinding binding) { + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .selections() + .reserve( + withIntent( + intent, + "changed notes", + intent.expectedVersionStateEpoch(), + intent.publishRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .selections() + .reserve( + withIntent( + intent, + intent.notes(), + "1", + intent.publishRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .selections() + .reserve( + withIntent( + intent, + intent.notes(), + intent.expectedVersionStateEpoch(), + "changed-request", + intent.selectedCommitId(), + intent.selectedCommitDigest())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .selections() + .reserve( + withIntent( + intent, + intent.notes(), + intent.expectedVersionStateEpoch(), + intent.publishRequestId(), + UUID.randomUUID(), + intent.selectedCommitDigest())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .selections() + .reserve( + withIntent( + intent, + intent.notes(), + intent.expectedVersionStateEpoch(), + intent.publishRequestId(), + intent.selectedCommitId(), + sha256("changed digest"))))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + } + + private static PublishIntent withIntent( + PublishIntent original, + String notes, + String expectedEpoch, + String requestId, + UUID selectedCommitId, + String selectedDigest) { + return new PublishIntent( + original.canonicalTenantId(), + original.canonicalVersionId(), + requestId, + expectedEpoch, + notes, + original.selectedCommitRequestId(), + selectedCommitId, + selectedDigest); + } + + private static PublishIntent intent( + VersionFixture version, DraftCommitBinding binding, String notes) { + return new PublishIntent( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + "publish-" + UUID.randomUUID(), + version.stateEpoch(), + notes, + binding.requestId(), + binding.commitId(), + binding.digest()); + } + + private static PublishIntent emptyIntent(VersionFixture version) { + return new PublishIntent( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + "publish-" + UUID.randomUUID(), + version.stateEpoch(), + "notes", + UUID.randomUUID(), + UUID.randomUUID(), + sha256("unselected")); + } + + private static DraftCommitBinding binding(TargetProof target, UUID requestId, UUID commitId) { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-source-7", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.WORLD_MANAGEMENT, + "{\"completeWorldMutation\":{\"opaque\":\"retained\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-17", + "ROOM_SCOPE", + "room-scope-5", + WORLD_EPOCH))); + } + + private static OwnerOutcome appliedOutcome(DraftCommitBinding binding) { + AffectedUnit expected = binding.affectedUnits(Owner.WORLD_MANAGEMENT).getFirst(); + String resultingEpoch = new BigInteger(expected.expectedEpoch()).add(BigInteger.ONE).toString(); + return new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "world-result-" + binding.commitId(), + ("full owner result " + binding.commitId()).getBytes(StandardCharsets.UTF_8), + List.of( + new AppliedEpoch( + expected.aggregateType(), + expected.aggregateId(), + expected.scopeType(), + expected.scopeId(), + expected.expectedEpoch(), + resultingEpoch))); + } + + private static Fixture createFixture() { + String schema = "gd_draft_select_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository games = new GameRepository(dsl); + VersionRepository versions = new VersionRepository(dsl, null); + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + AuthoredDraftPublishSelectionRepository selections = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator); + return new Fixture(dsl, transaction, games, versions, coordinator, selections); + } + + private static T inTransaction(Supplier work) { + return fixture.ownerTransaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for authored Draft selection race"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while racing authored Draft selection", exception); + } + } + + private static String sha256(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private record VersionFixture(TargetProof target, long rowId, String stateEpoch) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate ownerTransaction, + GameRepository games, + VersionRepository versions, + DraftCommitCoordinatorRepository coordinator, + AuthoredDraftPublishSelectionRepository selections) { + VersionFixture newVersion(long stateEpoch) { + String tenantKey = "d-" + UUID.randomUUID().toString().replace("-", ""); + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Authored Draft selection source"); + game.setDescription("Canonical Version reuse fixture"); + Game savedGame = Objects.requireNonNull(ownerTransaction.execute(status -> games.save(game))); + + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(stateEpoch); + Version savedVersion = + Objects.requireNonNull(ownerTransaction.execute(status -> versions.save(version))); + return new VersionFixture( + target(savedVersion), savedVersion.getId(), Long.toString(stateEpoch)); + } + + VersionFixture newScriptOnlyVersion(VersionFixture base) { + Version version = new Version(); + version.setTenantId(base.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setScriptOnly(true); + version.setScriptPatchVersion("patch-1"); + version.setBaseVersionId(base.rowId()); + Version savedVersion = + Objects.requireNonNull(ownerTransaction.execute(status -> versions.save(version))); + return new VersionFixture(target(savedVersion), savedVersion.getId(), "1"); + } + + void synchronize(DraftCommitBinding binding) { + ownerTransaction.executeWithoutResult( + status -> { + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + OwnerOutcome outcome = appliedOutcome(binding); + coordinator.recordOwnerOutcome(binding, outcome); + coordinator.advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + coordinator.releaseApplicationSlot(binding); + }); + } + + long versionCount() { + return dsl.fetchCount(DSL.table(DSL.name("version"))); + } + + private TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java new file mode 100644 index 0000000000..0a16d60cca --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java @@ -0,0 +1,877 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.ApplicationSlot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CommitSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.FinalAbortReceipt; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerState; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.WorkflowState; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class DraftCommitCoordinatorRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static Fixture fixture; + + @BeforeAll + static void setUpSchema() { + fixture = createFixture(); + } + + @Test + void exactClaimReplayRetainsFullBindingAndChangedRetryConflictsWithoutRewrite() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + + CommitSnapshot first = inTransaction(() -> fixture.coordinator().claim(binding)); + OffsetDateTimePair firstTimes = + new OffsetDateTimePair( + first.createdAt(), first.ownerStates().get(Owner.WORLD_MANAGEMENT).updatedAt()); + CommitSnapshot exactReplay = inTransaction(() -> fixture.coordinator().claim(binding)); + + assertThat(exactReplay.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(exactReplay.binding().digest()).isEqualTo(binding.digest()); + assertThat(exactReplay.createdAt()).isEqualTo(firstTimes.commitCreatedAt()); + assertThat(exactReplay.ownerStates().get(Owner.WORLD_MANAGEMENT).updatedAt()) + .isEqualTo(firstTimes.ownerUpdatedAt()); + assertThat(exactReplay.ownerStates().values()) + .allMatch(state -> state.status() == OwnerStatus.NOT_ATTEMPTED); + + var changed = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + new RevisionPayload( + "0", + binding.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "{\"room\":\"changed but still typed input\"}"), + binding.revisions().get(1)), + binding.affectedUnits()); + assertThatThrownBy(() -> inTransaction(() -> fixture.coordinator().claim(changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + } + + @Test + void pendingBindingAndOwnerRowsRollBackTogether() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + + fixture + .ownerTransaction() + .executeWithoutResult( + status -> { + fixture.coordinator().claim(binding); + status.setRollbackOnly(); + }); + + assertThat(fixture.coordinator().read(target, binding.requestId())).isEmpty(); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + } + + @Test + void concurrentExactClaimsConvergeOnOneImmutableBinding() throws Exception { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future left = + executor.submit( + () -> { + ready.countDown(); + await(start); + return inTransaction(() -> fixture.coordinator().claim(binding)); + }); + Future right = + executor.submit( + () -> { + ready.countDown(); + await(start); + return inTransaction(() -> fixture.coordinator().claim(binding)); + }); + await(ready); + start.countDown(); + CommitSnapshot first = left.get(20, TimeUnit.SECONDS); + CommitSnapshot second = right.get(20, TimeUnit.SECONDS); + + assertThat(first.binding().canonicalBytes()) + .containsExactly(second.binding().canonicalBytes()); + assertThat(fixture.coordinator().read(target, binding.requestId())).isPresent(); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(binding.requestId()))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void partialUnknownOwnerResultKeepsApplicationSlotAndCannotCreateVisibilityFence() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(binding)); + ApplicationSlot slot = inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding)); + assertThat(slot.commitId()).isEqualTo(binding.commitId()); + + inTransaction( + () -> { + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(binding, appliedWorldOutcome(binding)); + fixture.coordinator().markOwnerInProgress(binding, Owner.ENTITY_MANAGEMENT); + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of())); + return null; + }); + + CommitSnapshot partial = fixture.coordinator().read(target, binding.requestId()).orElseThrow(); + assertThat(partial.workflowState()).isEqualTo(WorkflowState.RECONCILIATION_REQUIRED); + assertThat(partial.ownerStates().get(Owner.WORLD_MANAGEMENT).status()) + .isEqualTo(OwnerStatus.APPLIED); + assertThat(partial.ownerStates().get(Owner.ENTITY_MANAGEMENT).status()) + .isEqualTo(OwnerStatus.UNKNOWN); + assertThat(fixture.coordinator().readApplicationSlot(target)).isPresent(); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + assertThatThrownBy( + () -> + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(binding); + return null; + })) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class) + .hasMessageContaining("cannot release"); + + OwnerState world = partial.ownerStates().get(Owner.WORLD_MANAGEMENT); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "world-result-exact-1", + "different bytes".getBytes(StandardCharsets.UTF_8), + appliedWorldOutcome(binding).appliedEpochs())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThat( + fixture + .coordinator() + .read(target, binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.WORLD_MANAGEMENT) + .updatedAt()) + .isEqualTo(world.updatedAt()); + } + + @Test + void exactAppliedResultReplayIsImmutableBeforeAndAfterSlotRelease() { + TargetProof target = fixture.newTarget(); + var binding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(binding)); + inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding)); + + OwnerOutcome original = appliedWorldOutcome(binding); + OwnerState first = + inTransaction( + () -> { + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + return fixture.coordinator().recordOwnerOutcome(binding, original); + }); + OwnerOutcome exactRetry = appliedWorldOutcome(binding); + OwnerState beforeRelease = + inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, exactRetry)); + assertThat(beforeRelease.updatedAt()).isEqualTo(first.updatedAt()); + assertThat(beforeRelease.outcome()).contains(original); + assertThat(beforeRelease.outcome().orElseThrow().resultBytes()) + .containsExactly(original.resultBytes()); + + OwnerOutcome changed = + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + original.resultIdentity(), + "changed owner evidence".getBytes(StandardCharsets.UTF_8), + original.appliedEpochs()); + assertThatThrownBy( + () -> inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + + inTransaction( + () -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(original))); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + + OwnerState afterRelease = + inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, exactRetry)); + assertThat(afterRelease.updatedAt()).isEqualTo(first.updatedAt()); + assertThat(afterRelease.outcome()).contains(original); + assertThat(afterRelease.outcome().orElseThrow().resultBytes()) + .containsExactly(original.resultBytes()); + } + + @Test + void mixedFinalAbortPreservesPriorFenceAndOwnerEvidenceAndFencesDelayedAttempts() { + TargetProof target = fixture.newTarget(); + var priorBinding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome priorWorld = appliedWorldOutcome(priorBinding); + inTransaction( + () -> { + fixture.coordinator().claim(priorBinding); + fixture.coordinator().claimApplicationSlot(priorBinding); + fixture.coordinator().markOwnerInProgress(priorBinding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(priorBinding, priorWorld); + fixture + .coordinator() + .advanceVisibilityFence( + priorBinding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + priorBinding, List.of(priorWorld))); + fixture.coordinator().releaseApplicationSlot(priorBinding); + return null; + }); + var priorFence = fixture.coordinator().readVisibilityFence(target).orElseThrow(); + + var failedBinding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome appliedWorld = appliedWorldOutcome(failedBinding); + OwnerOutcome rejectedEntity = + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.REJECTED, + failedBinding.commitId(), + failedBinding.digest(), + "entity-rejected-final-1", + "durable exact rejection".getBytes(StandardCharsets.UTF_8), + List.of()); + byte[] abortBytes = "trusted producer final-abort receipt".getBytes(StandardCharsets.UTF_8); + inTransaction( + () -> { + fixture.coordinator().claim(failedBinding); + fixture.coordinator().claimApplicationSlot(failedBinding); + fixture.coordinator().markOwnerInProgress(failedBinding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(failedBinding, appliedWorld); + fixture.coordinator().markOwnerInProgress(failedBinding, Owner.ENTITY_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(failedBinding, rejectedEntity); + return null; + }); + + FinalAbortReceipt first = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + CommitSnapshot failed = + fixture.coordinator().read(target, failedBinding.requestId()).orElseThrow(); + assertThat(failed.workflowState()).isEqualTo(WorkflowState.FAILED_NONPUBLICATION); + assertThat(failed.ownerStates().get(Owner.WORLD_MANAGEMENT).outcome()).contains(appliedWorld); + assertThat(failed.ownerStates().get(Owner.ENTITY_MANAGEMENT).outcome()) + .contains(rejectedEntity); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + + FinalAbortReceipt exactReplay = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + assertThat(exactReplay.binding()).isEqualTo(first.binding()); + assertThat(exactReplay.abortBytes()).containsExactly(first.abortBytes()); + assertThat(exactReplay.createdAt()).isEqualTo(first.createdAt()); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + failedBinding, + "changed final-abort bytes".getBytes(StandardCharsets.UTF_8)))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + + assertThat( + inTransaction( + () -> fixture.coordinator().recordOwnerOutcome(failedBinding, appliedWorld)) + .outcome()) + .contains(appliedWorld); + OwnerOutcome changedWorld = + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + failedBinding.commitId(), + failedBinding.digest(), + appliedWorld.resultIdentity(), + "changed World result".getBytes(StandardCharsets.UTF_8), + appliedWorld.appliedEpochs()); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.coordinator().recordOwnerOutcome(failedBinding, changedWorld))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + + assertThatThrownBy( + () -> inTransaction(() -> fixture.coordinator().claimApplicationSlot(failedBinding))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .markOwnerInProgress(failedBinding, Owner.WORLD_MANAGEMENT))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result " + + "SET status = 'IN_PROGRESS', updated_at = CURRENT_TIMESTAMP " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = 'WORLD_MANAGEMENT'", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId()))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility_fence " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, result_vector_json) " + + "VALUES (?, ?, ?, ?, ?, '[]')", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId(), + failedBinding.commitId(), + failedBinding.digest()))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId(), + failedBinding.commitId()))) + .isInstanceOf(RuntimeException.class); + + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(failedBinding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + + var laterBinding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction( + () -> { + fixture.coordinator().claim(laterBinding); + fixture.coordinator().claimApplicationSlot(laterBinding); + return null; + }); + FinalAbortReceipt replayAfterReclaim = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + assertThat(replayAfterReclaim.createdAt()).isEqualTo(first.createdAt()); + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(failedBinding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target).orElseThrow().requestId()) + .isEqualTo(laterBinding.requestId()); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + } + + @Test + void unknownOwnerAndMissingRowsCannotProduceFinalAbort() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome world = appliedWorldOutcome(binding); + inTransaction( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(binding, world); + fixture.coordinator().markOwnerInProgress(binding, Owner.ENTITY_MANAGEMENT); + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of())); + return null; + }); + + byte[] abortBytes = "not enough proof".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(binding, abortBytes))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(WorkflowState.RECONCILIATION_REQUIRED); + assertThat(fixture.coordinator().readApplicationSlot(target)).isPresent(); + + assertThatThrownBy( + () -> + inTransaction( + () -> { + fixture + .dsl() + .execute( + "DELETE FROM game_design_draft_commit_owner_result " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = 'ENTITY_MANAGEMENT'", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_final_abort " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, binding_json, abort_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + abortBytes))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void allAppliedOwnersIncludingGameDesignCanBeFinalAbortedWithoutVisibility() { + TargetProof target = fixture.newTarget(); + var binding = allOwnerBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + for (Owner owner : binding.requiredOwners()) { + OwnerOutcome outcome = appliedOutcome(binding, owner); + fixture.coordinator().markOwnerInProgress(binding, owner); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + } + return null; + }); + + FinalAbortReceipt receipt = + inTransaction( + () -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + binding, + "Game Design final no-commit proof".getBytes(StandardCharsets.UTF_8))); + CommitSnapshot snapshot = fixture.coordinator().read(target, binding.requestId()).orElseThrow(); + assertThat(snapshot.workflowState()).isEqualTo(WorkflowState.FAILED_NONPUBLICATION); + assertThat(snapshot.ownerStates()).containsKeys(Owner.GAME_DESIGN_CONTROL_PLANE); + assertThat(snapshot.ownerStates().values()) + .allMatch(state -> state.status() == OwnerStatus.APPLIED); + assertThat(receipt.binding()).isEqualTo(binding); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + List allApplied = + binding.requiredOwners().stream().map(owner -> appliedOutcome(binding, owner)).toList(); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, allApplied)))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + } + + @Test + void directSqlFinalAbortRejectsMissingRequiredOwnerRows() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + byte[] abortBytes = "missing owner is not no-commit proof".getBytes(StandardCharsets.UTF_8); + inTransaction( + () -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit " + + "(canonical_tenant_id, canonical_version_id, " + + "game_design_version_row_id, game_design_version_tenant_key, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, " + + "request_id, commit_id, base_commit_id, input_digest, binding_json, " + + "workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'APPLYING')", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId()); + return null; + }); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(binding.requestId()))) + .isEqualTo(1); + assertThat(fixture.coordinator().readApplicationSlot(target).orElseThrow().requestId()) + .isEqualTo(binding.requestId()); + + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_final_abort " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, binding_json, abort_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + abortBytes))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Final-abort evidence requires every exact owner result to be terminal"); + } + + private static Fixture createFixture() { + String schema = "gd_draft_coord_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl, null); + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + return new Fixture(dsl, transactionTemplate, gameRepository, versionRepository, coordinator); + } + + private static DraftCommitBinding binding(TargetProof target, UUID requestId, UUID commitId) { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-source-7", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.WORLD_MANAGEMENT, + "{\"completeWorldMutation\":{\"opaque\":\"preserved\"}}"), + new RevisionPayload( + "1", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "{\"completeEntityMutation\":{\"opaque\":\"preserved\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-scope-1", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-1", + "ACTOR_SCOPE", + "actor-scope-1", + "0"))); + } + + private static DraftCommitBinding worldOnlyBinding( + TargetProof target, UUID requestId, UUID commitId) { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-source-7", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.WORLD_MANAGEMENT, + "{\"completeWorldMutation\":{\"opaque\":\"preserved\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-scope-1", + LARGE_EPOCH))); + } + + private static DraftCommitBinding allOwnerBinding( + TargetProof target, UUID requestId, UUID commitId) { + List revisions = new java.util.ArrayList<>(); + List affected = new java.util.ArrayList<>(); + int index = 0; + for (Owner owner : Owner.values()) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + owner, + "{\"ownerMutation\":\"" + owner.name() + "\"}")); + affected.add( + new AffectedUnit( + owner, + owner.name() + "_AGGREGATE", + "aggregate-" + owner.name().toLowerCase(java.util.Locale.ROOT), + owner.name() + "_SCOPE", + "scope-" + owner.name().toLowerCase(java.util.Locale.ROOT), + "0")); + index++; + } + return DraftCommitBinding.create( + target, requestId, commitId, "base-commit-source-7", revisions, affected); + } + + private static OwnerOutcome appliedOutcome(DraftCommitBinding binding, Owner owner) { + AffectedUnit expected = binding.affectedUnits(owner).getFirst(); + String resultingEpoch = + new java.math.BigInteger(expected.expectedEpoch()).add(java.math.BigInteger.ONE).toString(); + return new OwnerOutcome( + owner, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + owner.name().toLowerCase(java.util.Locale.ROOT) + "-result-exact-1", + ("full durable " + owner.name() + " response").getBytes(StandardCharsets.UTF_8), + List.of( + new AppliedEpoch( + expected.aggregateType(), + expected.aggregateId(), + expected.scopeType(), + expected.scopeId(), + expected.expectedEpoch(), + resultingEpoch))); + } + + private static OwnerOutcome appliedWorldOutcome(DraftCommitBinding binding) { + AffectedUnit expected = binding.affectedUnits(Owner.WORLD_MANAGEMENT).getFirst(); + String resultingEpoch = + new java.math.BigInteger(expected.expectedEpoch()).add(java.math.BigInteger.ONE).toString(); + return new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "world-result-exact-1", + "full durable owner response".getBytes(StandardCharsets.UTF_8), + List.of( + new AppliedEpoch( + expected.aggregateType(), + expected.aggregateId(), + expected.scopeType(), + expected.scopeId(), + expected.expectedEpoch(), + resultingEpoch))); + } + + private static T inTransaction(Supplier work) { + return fixture.ownerTransaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent Draft commit claim"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while coordinating concurrent Draft claims", exception); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate ownerTransaction, + GameRepository games, + VersionRepository versions, + DraftCommitCoordinatorRepository coordinator) { + TargetProof newTarget() { + String tenantKey = "d-" + UUID.randomUUID().toString().replace("-", ""); + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Draft coordinator integration source"); + game.setDescription("Canonical Version source fixture"); + Game savedGame = Objects.requireNonNull(ownerTransaction.execute(status -> games.save(game))); + + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(net.firedevops.firemud.gamedesign.model.VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = + Objects.requireNonNull(ownerTransaction.execute(status -> versions.save(version))); + return new TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + } + } + + private record OffsetDateTimePair( + java.time.OffsetDateTime commitCreatedAt, java.time.OffsetDateTime ownerUpdatedAt) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java new file mode 100644 index 0000000000..1814a0320d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -0,0 +1,144 @@ +package unit.net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; +import org.junit.jupiter.api.Test; + +class AuthoredDraftPublishSelectionTest { + private static final String LARGE_COUNTER = "900719925474099312345678901234567890"; + + @Test + void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() { + TargetProof target = target(); + DraftCommitBinding binding = binding(target); + VisibilityFence fence = + new VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[{\"appliedEpochs\":[{\"aggregateId\":\"world-17\"," + + "\"aggregateType\":\"WORLD_TEMPLATE\",\"expectedEpoch\":\"" + + LARGE_COUNTER + + "\",\"resultingEpoch\":\"900719925474099312345678901234567891\"," + + "\"scopeId\":\"room-scope-5\",\"scopeType\":\"ROOM_SCOPE\"}]," + + "\"bindingDigest\":\"" + + binding.digest() + + "\",\"commitId\":\"" + + binding.commitId() + + "\",\"owner\":\"WORLD_MANAGEMENT\",\"resultBytesBase64\":\"YXBwbGllZA==\"," + + "\"resultIdentity\":\"world-result-1\",\"status\":\"APPLIED\"}]", + OffsetDateTime.parse("2026-10-05T00:00:00Z")); + PublishIntent intent = + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-request-é", + LARGE_COUNTER, + "Exact creator notes — preserve spacing ", + binding.requestId(), + binding.commitId(), + binding.digest()); + + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + AuthoredDraftPublishSelection restored = + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()); + + assertThat(restored).isEqualTo(selection); + assertThat(restored.intent().notes()).isEqualTo(intent.notes()); + assertThat(restored.intent().expectedVersionStateEpoch()).isEqualTo(LARGE_COUNTER); + assertThat(restored.canonicalJson()) + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedVersionStateEpoch\":\"" + LARGE_COUNTER + "\""); + assertThat(restored.selectedCommit().canonicalJson()).isEqualTo(binding.canonicalJson()); + assertThat(restored.fenceResultVectorJson()).isEqualTo(fence.resultVectorJson()); + assertThat(restored.fenceCreatedAt()).isEqualTo("2026-10-05T00:00:00Z"); + } + + @Test + void rejectsInvalidSelectionEpochAndChangedIntent() { + TargetProof target = target(); + DraftCommitBinding binding = binding(target); + PublishIntent original = intent(target, binding, "original notes"); + + assertThatThrownBy( + () -> + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + original.publishRequestId(), + "01", + original.notes(), + binding.requestId(), + binding.commitId(), + binding.digest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive canonical decimal"); + assertThat(original).isNotEqualTo(intent(target, binding, "changed notes")); + } + + private static TargetProof target() { + return new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"); + } + + private static DraftCommitBinding binding(TargetProof target) { + return DraftCommitBinding.create( + target, + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-exact-9", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\"fullTypedMutation\":{\"unknown\":\"retained\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-17", + "ROOM_SCOPE", + "room-scope-5", + LARGE_COUNTER))); + } + + private static PublishIntent intent( + TargetProof target, DraftCommitBinding binding, String notes) { + return new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-request-7", + LARGE_COUNTER, + notes, + binding.requestId(), + binding.commitId(), + binding.digest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/DraftCommitBindingTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/DraftCommitBindingTest.java new file mode 100644 index 0000000000..b50b7ef202 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/DraftCommitBindingTest.java @@ -0,0 +1,224 @@ +package unit.net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +class DraftCommitBindingTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Test + void canonicalBindingRetainsCompleteOpaqueInputsAndDecimalCounters() { + DraftCommitBinding binding = binding(); + DraftCommitBinding restored = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + + assertThat(restored).isEqualTo(binding); + assertThat(binding.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedEpoch\":\"" + LARGE_EPOCH + "\"") + .contains("unknownTypedField") + .contains("\\n \\\"full\\\": true"); + assertThat(binding.requiredOwners()) + .containsExactly(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(binding.affectedUnits()) + .extracting(AffectedUnit::aggregateType, AffectedUnit::aggregateId) + .containsExactly( + org.assertj.core.groups.Tuple.tuple("WORLD_TEMPLATE", "world-23"), + org.assertj.core.groups.Tuple.tuple("ENTITY_TEMPLATE", "entity-17")); + + byte[] firstRead = binding.canonicalBytes(); + firstRead[0] = (byte) (firstRead[0] ^ 1); + assertThat(binding.canonicalBytes()).isNotEqualTo(firstRead); + assertThat(new String(binding.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(binding.canonicalJson()); + } + + @Test + void canonicalBindingIsStableAcrossAffectedInputOrder() { + DraftCommitBinding first = binding(); + DraftCommitBinding reordered = + DraftCommitBinding.create( + first.target(), + first.requestId(), + first.commitId(), + first.baseCommitId(), + first.revisions(), + List.of(first.affectedUnits().get(1), first.affectedUnits().get(0))); + + assertThat(reordered.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(reordered.digest()).isEqualTo(first.digest()); + } + + @Test + void collectionAccessorsReturnImmutableCopies() { + DraftCommitBinding binding = binding(); + + assertThatThrownBy(() -> binding.revisions().add(binding.revisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.affectedUnits().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.requiredOwners().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsMissingOrNonArrayStoredCollections() { + DraftCommitBinding original = binding(); + ObjectMapper json = new ObjectMapper(); + + ObjectNode missingRevisions = (ObjectNode) json.readTree(original.canonicalJson()); + missingRevisions.remove("revisions"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(missingRevisions), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + + ObjectNode invalidAffectedUnits = (ObjectNode) json.readTree(original.canonicalJson()); + invalidAffectedUnits.put("affectedUnits", "not-an-array"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(invalidAffectedUnits), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + } + + @Test + void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { + DraftCommitBinding original = binding(); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner set"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0), original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical array order"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + original.revisions(), + List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate affected"); + } + + @Test + void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { + DraftCommitBinding original = binding(); + AffectedUnit affected = original.affectedUnits().getFirst(); + assertThatThrownBy( + () -> + new AffectedUnit( + affected.owner(), + affected.aggregateType(), + affected.aggregateId(), + affected.scopeType(), + affected.scopeId(), + "01")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + assertThatThrownBy( + () -> + new TargetProof( + new UUID(0L, 0L), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "tenant-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new TargetProof( + original.target().canonicalTenantId(), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "different-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must match exactly"); + } + + private DraftCommitBinding binding() { + return DraftCommitBinding.create( + new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"), + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-opaque-01", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\n \"full\": true, \"unknownTypedField\": {\"keep\": \"all\"}\n}"), + new RevisionPayload( + "1", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.ENTITY_MANAGEMENT, + "{\"actorTemplate\":{\"complete\":true}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-17", + "ACTOR_SCOPE", + "actor-scope-2", + "0"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java new file mode 100644 index 0000000000..5d88703b73 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java @@ -0,0 +1,206 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable, owner-private capture of the six authored World template families. */ +public record WorldAuthoredGraphSnapshot( + UUID snapshotId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + short ownerBindingSchemaVersion, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String captureRequestDigest, + String suppliedOwnedAffectedTuplesJson, + String ownerRevisionEvidenceJson, + byte[] graphBytes, + String graphSha256, + OwnerCommitProofStatus ownerCommitProofStatus) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public WorldAuthoredGraphSnapshot { + requireNonNil(snapshotId, "snapshotId"); + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requireText(worldSlug, "worldSlug"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + requirePositive(localVersionKey, "localVersionKey"); + requirePositive(localTenantKey, "localTenantKey"); + if (ownerBindingSchemaVersion != 1) { + throw new IllegalArgumentException( + "World snapshot requires exact V27 owner binding schema 1"); + } + requireNonNil(intakeOperationId, "intakeOperationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requirePrefixedSha256(intakeRequestDigest, "intakeRequestDigest"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requirePrefixedSha256(sourceEvidenceDigest, "sourceEvidenceDigest"); + requirePrefixedSha256(intakeReceiptDigest, "intakeReceiptDigest"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2) { + throw new IllegalArgumentException("World graph snapshot requires digest schema version 2"); + } + requireSha256(captureRequestDigest, "captureRequestDigest"); + requireText(suppliedOwnedAffectedTuplesJson, "suppliedOwnedAffectedTuplesJson"); + requireText(ownerRevisionEvidenceJson, "ownerRevisionEvidenceJson"); + graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + if (graphBytes.length == 0) { + throw new IllegalArgumentException("graphBytes must contain a complete graph representation"); + } + requireSha256(graphSha256, "graphSha256"); + Objects.requireNonNull(ownerCommitProofStatus, "ownerCommitProofStatus"); + if (ownerCommitProofStatus != OwnerCommitProofStatus.CAPTURED_UNVERIFIED) { + throw new IllegalArgumentException( + "This component cannot claim complete owner commit application proof"); + } + } + + @Override + public byte[] graphBytes() { + return graphBytes.clone(); + } + + /** Proof state is deliberately non-eligible until the complete World commit fence is wired. */ + public enum OwnerCommitProofStatus { + CAPTURED_UNVERIFIED + } + + /** One supplied World-owned affected tuple, retained as input evidence without validating it. */ + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("World snapshot tuples must name WORLD_MANAGEMENT"); + } + requireText(aggregateType, "aggregateType"); + requireText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException( + "scopeType and scopeId must be both present or both absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + } + + /** Exact external binding. All private World keys are resolved from immutable owner records. */ + public record CaptureRequest( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List suppliedOwnedAffectedTuples) { + public CaptureRequest { + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2) { + throw new IllegalArgumentException("World graph snapshot requires digest schema version 2"); + } + Objects.requireNonNull(suppliedOwnedAffectedTuples, "suppliedOwnedAffectedTuples"); + List ordered = new ArrayList<>(suppliedOwnedAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + for (int index = 1; index < ordered.size(); index++) { + if (ordered.get(index - 1).equals(ordered.get(index))) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + } + suppliedOwnedAffectedTuples = List.copyOf(ordered); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " is required"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be 64 lowercase hexadecimal digits"); + } + } + + private static void requirePrefixedSha256(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java new file mode 100644 index 0000000000..ca8bbea36a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -0,0 +1,624 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.OwnerProvenance; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal-only World graph snapshot capture. Captured rows are representation evidence, not + * publication eligibility or proof that World applied a complete synchronized owner commit. + */ +public class WorldAuthoredGraphSnapshotCapture { + private static final int GRAPH_SCHEMA_VERSION = 1; + private static final int WORLD_DIGEST_SCHEMA_VERSION = 2; + + private static final Table REGION = table("region"); + private static final Table ZONE = table("zone"); + private static final Table ROOM = table("room"); + private static final Table ROOM_EXIT = table("room_exit"); + private static final Table GENERATION_RULE = table("generation_rule"); + private static final Table SPAWN_BINDING = table("world_entity_spawn_binding"); + private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field REGION_ID = field("region_id", Long.class); + private static final Field ZONE_ID = field("zone_id", Long.class); + private static final Field FROM_ROOM_ID = field("from_room_id", Long.class); + private static final Field TO_ROOM_ID = field("to_room_id", Long.class); + private static final Field ROOM_ID = field("room_id", Long.class); + private static final Field GENERATION_SEED = field("generation_seed", Long.class); + private static final Field SHARD_ID = field("shard_id", Integer.class); + private static final Field NAME = field("name", String.class); + private static final Field WEATHER = field("weather", String.class); + private static final Field GENERATOR_TYPE = field("generator_type", String.class); + private static final Field GENERATOR_PARAMS = field("generator_params", String.class); + private static final Field SPACING_MULTIPLIER = field("spacing_multiplier", Double.class); + private static final Field DESCRIPTION = field("description", String.class); + private static final Field NAME_LOCALIZED_VARIANTS_JSON = + field("name_localized_variants_json", String.class); + private static final Field DESCRIPTION_LOCALIZED_VARIANTS_JSON = + field("description_localized_variants_json", String.class); + private static final Field DIRECTION = field("direction", String.class); + private static final Field COST = field("cost", Integer.class); + private static final Field SCOPE_TYPE = field("scope_type", String.class); + private static final Field SCOPE_ID = field("scope_id", String.class); + private static final Field RULE_VALUE = field("value", String.class); + private static final Field ENTITY_TEMPLATE_TYPE = + field("entity_template_type", String.class); + private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); + private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); + private static final Field RESPAWN_DELAY_SECONDS = + field("respawn_delay_seconds", Integer.class); + + private static final Field COMMIT_ID = field("commit_id", String.class); + private static final Field REVISION_ID = field("revision_id", String.class); + private static final Field OPERATION_TYPE = field("operation_type", String.class); + private static final Field AGGREGATE_TYPE = field("aggregate_type", String.class); + private static final Field REQUESTED_AGGREGATE_ID = + field("requested_aggregate_id", String.class); + private static final Field APPLIED_AGGREGATE_ID = field("applied_aggregate_id", Long.class); + private static final Field RESULT = field("result", String.class); + private static final Field AGGREGATE_EPOCH_AFTER = + field("aggregate_epoch_after", Long.class); + private static final Field SCOPE_EPOCH_AFTER = field("scope_epoch_after", Long.class); + + private final DSLContext dsl; + private final WorldDraftDesignDigestService draftDigestService; + private final WorldAuthoredGraphSnapshotRepository snapshotRepository; + private final ObjectMapper objectMapper; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected World collaborators are internal; construction acquires no resources and this class has no finalizer.") + public WorldAuthoredGraphSnapshotCapture( + DSLContext dsl, + WorldDraftDesignDigestService draftDigestService, + WorldAuthoredGraphSnapshotRepository snapshotRepository, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.draftDigestService = + Objects.requireNonNull(draftDigestService, "draftDigestService must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); + } + + /** + * Captures the current six-family authored graph while holding the exact V25 owner row. + * + *

The caller owns the writable READ COMMITTED transaction. This method is deliberately unwired + * from public publication/activation surfaces and persists every result as {@code + * CAPTURED_UNVERIFIED}; V19 currently lacks the revision-to-complete-scope proof needed to claim + * synchronized owner application. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + OwnerProvenance provenance = snapshotRepository.lockAndResolve(request); + String tuplesJson = encodeTuples(request.suppliedOwnedAffectedTuples()); + String captureRequestDigest = captureRequestDigest(request, provenance, tuplesJson); + + WorldAuthoredGraphSnapshot prior = snapshotRepository.findByFence(request.publicationFence()); + if (prior != null) { + snapshotRepository.requireSameRequest( + prior, request, provenance, captureRequestDigest, tuplesJson); + return prior; + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new SnapshotConflictException( + "World graph capture cannot create a new snapshot after its V25 fence leaves FROZEN"); + } + + String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); + Graph graph = readAndValidateGraph(provenance); + byte[] graphBytes = encodeGraph(graph); + WorldDraftDesignDigest currentDigest = + draftDigestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(currentDigest.tenantId()) + || currentDigest.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION + || !request.contentDigest().equals(currentDigest.contentDigest())) { + throw new SnapshotConflictException( + "World graph capture differs from the V25 frozen checkpoint under the V27 private Version key"); + } + + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + newNonNilUuid(), + provenance.targetNamespace(), + provenance.canonicalTenantId(), + provenance.canonicalVersionId(), + provenance.versionIdentityOperationId(), + provenance.worldSlug(), + provenance.gameDesignVersionId(), + provenance.localVersionKey(), + provenance.localTenantKey(), + (short) 1, + provenance.intakeOperationId(), + provenance.intakeRequestId(), + provenance.intakeRequestDigest(), + provenance.sourceOperationId(), + provenance.sourceEvidenceDigest(), + provenance.intakeReceiptDigest(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + captureRequestDigest, + tuplesJson, + revisionEvidenceJson, + graphBytes, + sha256(graphBytes), + OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + return snapshotRepository.insertAndReadback(snapshot); + } + + private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvenance provenance) { + Result rows = + dsl.select( + ID, + COMMIT_ID, + REVISION_ID, + OPERATION_TYPE, + AGGREGATE_TYPE, + REQUESTED_AGGREGATE_ID, + APPLIED_AGGREGATE_ID, + RESULT, + AGGREGATE_EPOCH_AFTER, + SCOPE_EPOCH_AFTER) + .from(REVISION_LEDGER) + .where( + TENANT_ID + .eq(provenance.localTenantKey()) + .and(VERSION_ID.eq(provenance.localVersionKey())) + .and(COMMIT_ID.eq(request.appliedCommitId()))) + .orderBy(ID.asc()) + .fetch(); + if (rows.isEmpty()) { + throw new WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException( + "World graph capture requires retained V19 revision history for the named commit"); + } + List> evidence = new ArrayList<>(); + for (Record row : rows) { + if (!"APPLIED".equals(row.get(RESULT, String.class))) { + throw new SnapshotConflictException( + "World graph capture encountered non-APPLIED V19 revision history"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", required(row, ID)); + item.put("commitId", required(row, COMMIT_ID)); + item.put("revisionId", required(row, REVISION_ID)); + item.put("operationType", required(row, OPERATION_TYPE)); + item.put("aggregateType", required(row, AGGREGATE_TYPE)); + item.put("requestedAggregateId", required(row, REQUESTED_AGGREGATE_ID)); + item.put("appliedAggregateId", required(row, APPLIED_AGGREGATE_ID)); + item.put("result", required(row, RESULT)); + item.put("aggregateEpochAfter", required(row, AGGREGATE_EPOCH_AFTER)); + item.put("scopeEpochAfter", row.get(SCOPE_EPOCH_AFTER, Long.class)); + evidence.add(item); + } + return writeJson(evidence); + } + + private Graph readAndValidateGraph(OwnerProvenance provenance) { + long tenantKey = provenance.localTenantKey(); + long versionKey = provenance.localVersionKey(); + List regionRows = fetch(REGION, tenantKey, versionKey); + List zoneRows = fetch(ZONE, tenantKey, versionKey); + List roomRows = fetch(ROOM, tenantKey, versionKey); + List exitRows = fetch(ROOM_EXIT, tenantKey, versionKey); + List ruleRows = fetch(GENERATION_RULE, tenantKey, versionKey); + List bindingRows = fetch(SPAWN_BINDING, tenantKey, versionKey); + + Map regionIds = new HashMap<>(); + Map zoneIds = new HashMap<>(); + Map roomIds = new HashMap<>(); + List> regions = new ArrayList<>(); + List> zones = new ArrayList<>(); + List> rooms = new ArrayList<>(); + List> exits = new ArrayList<>(); + List> rules = new ArrayList<>(); + List> bindings = new ArrayList<>(); + + for (Record row : regionRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "region.id"); + unique(regionIds, id, "region"); + Integer shard = required(row, SHARD_ID); + Long seed = required(row, GENERATION_SEED); + Double spacing = required(row, SPACING_MULTIPLIER); + String name = required(row, NAME); + if (shard < 0 || !Double.isFinite(spacing) || spacing <= 0.0d || name.isBlank()) { + throw incomplete("region", id, "unsupported required region data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("shardId", shard); + item.put("name", name); + item.put("weather", row.get(WEATHER, String.class)); + item.put("generationSeed", seed); + item.put("generatorType", row.get(GENERATOR_TYPE, String.class)); + item.put("generatorParams", row.get(GENERATOR_PARAMS, String.class)); + item.put("spacingMultiplier", spacing); + regions.add(item); + } + + for (Record row : zoneRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "zone.id"); + unique(zoneIds, id, "zone"); + long regionId = positive(row, REGION_ID, "zone.region_id"); + if (!regionIds.containsKey(regionId)) { + throw incomplete( + "zone", id, "region parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("zone", id, "zone name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("regionId", regionId); + item.put("name", name); + zones.add(item); + } + + for (Record row : roomRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room.id"); + unique(roomIds, id, "room"); + long zoneId = positive(row, ZONE_ID, "room.zone_id"); + if (!zoneIds.containsKey(zoneId)) { + throw incomplete("room", id, "zone parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("room", id, "room name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("zoneId", zoneId); + item.put("name", name); + item.put("description", row.get(DESCRIPTION, String.class)); + item.put("nameLocalizedVariantsJson", row.get(NAME_LOCALIZED_VARIANTS_JSON, String.class)); + item.put( + "descriptionLocalizedVariantsJson", + row.get(DESCRIPTION_LOCALIZED_VARIANTS_JSON, String.class)); + rooms.add(item); + } + + for (Record row : exitRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room_exit.id"); + long from = positive(row, FROM_ROOM_ID, "room_exit.from_room_id"); + long to = positive(row, TO_ROOM_ID, "room_exit.to_room_id"); + if (!roomIds.containsKey(from) || !roomIds.containsKey(to)) { + throw incomplete( + "room_exit", id, "exit endpoint is missing or belongs to another tenant/Version"); + } + String direction = required(row, DIRECTION); + Integer cost = required(row, COST); + if (direction.isBlank() || cost <= 0) { + throw incomplete("room_exit", id, "unsupported required room-exit data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("fromRoomId", from); + item.put("toRoomId", to); + item.put("direction", direction); + item.put("cost", cost); + exits.add(item); + } + + Set exactRuleKeys = new HashSet<>(); + Set unscopedRuleNames = new HashSet<>(); + for (Record row : ruleRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "generation_rule.id"); + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("generation_rule", id, "generation rule name is blank"); + } + String scopeType = row.get(SCOPE_TYPE, String.class); + String scopeId = row.get(SCOPE_ID, String.class); + if ((scopeType == null) != (scopeId == null)) { + throw incomplete( + "generation_rule", id, "scope_type and scope_id are only partially present"); + } + String stableScope; + if (scopeType == null) { + if (!unscopedRuleNames.add(name)) { + throw incomplete( + "generation_rule", id, "duplicate ambiguous unscoped generation rule name"); + } + stableScope = ""; + } else { + if (!"REGION_SUBTREE".equals(scopeType) && !"ZONE_SUBTREE".equals(scopeType)) { + throw incomplete("generation_rule", id, "unsupported generation rule scope type"); + } + long parsedScopeId = parseCanonicalPositiveId(scopeId, "generation_rule.scope_id", id); + if (("REGION_SUBTREE".equals(scopeType) && !regionIds.containsKey(parsedScopeId)) + || ("ZONE_SUBTREE".equals(scopeType) && !zoneIds.containsKey(parsedScopeId))) { + throw incomplete( + "generation_rule", id, "generation rule scope parent is missing or mismatched"); + } + stableScope = scopeType + ":" + scopeId; + } + if (!exactRuleKeys.add(stableScope + "\u0000" + name)) { + throw incomplete("generation_rule", id, "duplicate generation rule identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("name", name); + item.put("scopeType", scopeType); + item.put("scopeId", scopeId); + item.put("value", row.get(RULE_VALUE, String.class)); + rules.add(item); + } + + Set spawnKeys = new HashSet<>(); + for (Record row : bindingRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "world_entity_spawn_binding.id"); + long roomId = positive(row, ROOM_ID, "world_entity_spawn_binding.room_id"); + if (!roomIds.containsKey(roomId)) { + throw incomplete( + "world_entity_spawn_binding", + id, + "spawn room is missing or belongs to another tenant/Version"); + } + String entityType = required(row, ENTITY_TEMPLATE_TYPE); + Long entityId = required(row, ENTITY_TEMPLATE_ID); + Integer spawnCount = required(row, SPAWN_COUNT); + Integer delay = required(row, RESPAWN_DELAY_SECONDS); + if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) + || entityId <= 0L + || spawnCount <= 0 + || delay < 0) { + throw incomplete( + "world_entity_spawn_binding", id, "unsupported required spawn binding data"); + } + String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; + if (!spawnKeys.add(spawnKey)) { + throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("roomId", roomId); + item.put("entityTemplateType", entityType); + item.put("entityTemplateId", entityId); + item.put("spawnCount", spawnCount); + item.put("respawnDelaySeconds", delay); + bindings.add(item); + } + return new Graph(regions, zones, rooms, exits, rules, bindings); + } + + private List fetch(Table table, long tenantKey, long versionKey) { + List fetchedRows = + dsl.selectFrom(table) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionKey))) + .orderBy(ID.asc()) + .fetch(); + List rows = new ArrayList<>(fetchedRows.size()); + rows.addAll(fetchedRows); + return rows; + } + + private void requireExactScope(Record row, long tenantKey, long versionKey) { + if (!Objects.equals(row.get(TENANT_ID, Long.class), tenantKey) + || !Objects.equals(row.get(VERSION_ID, Long.class), versionKey)) { + throw new SnapshotConflictException( + "World graph row returned outside the exact V27 tenant/Version scope"); + } + } + + private long positive(Record row, Field field, String label) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new SnapshotConflictException(label + " is missing or non-positive"); + } + return value; + } + + private long parseCanonicalPositiveId(String value, String label, long rowId) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new NumberFormatException("not canonical positive decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw incomplete("generation_rule", rowId, label + " is unsupported"); + } + } + + private byte[] encodeGraph(Graph graph) { + LinkedHashMap root = new LinkedHashMap<>(); + root.put("snapshotSchemaVersion", GRAPH_SCHEMA_VERSION); + root.put("regions", graph.regions()); + root.put("zones", graph.zones()); + root.put("rooms", graph.rooms()); + root.put("roomExits", graph.roomExits()); + root.put("generationRules", graph.generationRules()); + root.put("worldEntitySpawnBindings", graph.spawnBindings()); + return writeJsonBytes(root); + } + + private String encodeTuples(List tuples) { + List> values = new ArrayList<>(); + for (OwnedAffectedTuple tuple : tuples) { + LinkedHashMap item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + values.add(item); + } + return writeJson(values); + } + + private String captureRequestDigest( + CaptureRequest request, OwnerProvenance provenance, String tuplesJson) { + LinkedHashMap binding = new LinkedHashMap<>(); + binding.put("targetNamespace", request.targetNamespace()); + binding.put("canonicalTenantId", request.canonicalTenantId().toString()); + binding.put("canonicalVersionId", request.canonicalVersionId().toString()); + binding.put("versionIdentityOperationId", provenance.versionIdentityOperationId().toString()); + binding.put("worldSlug", provenance.worldSlug()); + binding.put("gameDesignVersionId", provenance.gameDesignVersionId()); + binding.put("localVersionKey", provenance.localVersionKey()); + binding.put("localTenantKey", provenance.localTenantKey()); + binding.put("intakeOperationId", provenance.intakeOperationId().toString()); + binding.put("intakeRequestId", request.intakeRequestId().toString()); + binding.put("intakeRequestDigest", provenance.intakeRequestDigest()); + binding.put("sourceOperationId", provenance.sourceOperationId().toString()); + binding.put("sourceEvidenceDigest", provenance.sourceEvidenceDigest()); + binding.put("intakeReceiptDigest", provenance.intakeReceiptDigest()); + binding.put("publicationFence", request.publicationFence().toString()); + binding.put("publicationRequestId", request.publicationRequestId()); + binding.put("requestDigest", request.requestDigest()); + binding.put("versionStateEpoch", request.versionStateEpoch()); + binding.put("publishWorkflowId", request.publishWorkflowId()); + binding.put("appliedCommitId", request.appliedCommitId()); + binding.put("contentDigest", request.contentDigest()); + binding.put("digestSchemaVersion", request.digestSchemaVersion()); + binding.put("suppliedOwnedAffectedTuplesJson", tuplesJson); + return sha256(writeJsonBytes(binding)); + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph evidence could not be encoded"); + } + } + + private byte[] writeJsonBytes(Object value) { + try { + return objectMapper.writeValueAsBytes(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private SnapshotConflictException incomplete(String family, long id, String reason) { + return new SnapshotConflictException( + "World graph capture denied incomplete " + family + " row " + id + ": " + reason); + } + + private void unique(Map ids, long id, String family) { + if (ids.putIfAbsent(id, Boolean.TRUE) != null) { + throw incomplete(family, id, "duplicate row identity"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder builder = new StringBuilder(digest.length * 2); + for (byte current : digest) { + builder.append(String.format("%02x", current)); + } + return builder.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private record Graph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java new file mode 100644 index 0000000000..749d06c7f6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java @@ -0,0 +1,599 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-private persistence for immutable World authored graph captures. */ +@Repository +public class WorldAuthoredGraphSnapshotRepository { + private static final String FROZEN = "FROZEN"; + private static final Set RETAINED_FENCE_PHASES = + Set.of(FROZEN, "PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED"); + private static final String CAPTURED_UNVERIFIED = "CAPTURED_UNVERIFIED"; + + private static final Table SNAPSHOT = DSL.table(DSL.name("world_authored_graph_snapshot")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + private static final Table FENCE_OWNER = + DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table FENCE_ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + + private static final Field SNAPSHOT_ID = field("snapshot_id", UUID.class); + private static final Field CAPTURE_REQUEST_DIGEST = + field("capture_request_digest", String.class); + private static final Field PUBLICATION_FENCE = field("publication_fence", UUID.class); + private static final Field TARGET_NAMESPACE = field("target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field WORLD_SLUG = field("world_slug", String.class); + private static final Field GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field REQUEST_DIGEST = field("request_digest", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field APPLIED_COMMIT_ID = field("applied_commit_id", String.class); + private static final Field CONTENT_DIGEST = field("content_digest", String.class); + private static final Field DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + private static final Field SUPPLIED_TUPLES_JSON = + field("supplied_owned_affected_tuples_json", String.class); + private static final Field OWNER_REVISION_EVIDENCE_JSON = + field("owner_revision_evidence_json", String.class); + private static final Field OWNER_COMMIT_PROOF_STATUS = + field("owner_commit_proof_status", String.class); + private static final Field GRAPH_BYTES = field("graph_bytes", byte[].class); + private static final Field GRAPH_SHA256 = field("graph_sha256", String.class); + + private static final Field VERSION_OPERATION_ID = field("operation_id", UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + + private static final Field INTAKE_OPERATION = field("operation_id", UUID.class); + private static final Field INTAKE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field INTAKE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INTAKE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field INTAKE_REQUEST = field("intake_request_id", UUID.class); + private static final Field INTAKE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field INTAKE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT = field("receipt_digest", String.class); + private static final Field INTAKE_WORLD_SLUG = field("world_slug", String.class); + + private static final Field OWNER_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field OWNER_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field OWNER_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_VERSION_ID = field("version_id", Long.class); + private static final Field OWNER_FREEZE_PHASE = field("owner_freeze_phase", String.class); + private static final Field OWNER_CURRENT_FENCE = + field("current_publication_fence", UUID.class); + + private static final Field ATTEMPT_FENCE = field("publication_fence", UUID.class); + private static final Field ATTEMPT_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field ATTEMPT_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field ATTEMPT_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field ATTEMPT_VERSION_ID = field("version_id", Long.class); + private static final Field ATTEMPT_OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field ATTEMPT_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field ATTEMPT_VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field ATTEMPT_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field ATTEMPT_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field ATTEMPT_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field ATTEMPT_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field ATTEMPT_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field ATTEMPT_PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field ATTEMPT_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field ATTEMPT_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field ATTEMPT_PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field ATTEMPT_APPLIED_COMMIT_ID = + field("applied_commit_id", String.class); + private static final Field ATTEMPT_CONTENT_DIGEST = field("content_digest", String.class); + private static final Field ATTEMPT_DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredGraphSnapshotRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Resolves all private keys and locks the existing V25 FROZEN owner row. */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProvenance lockAndResolve(CaptureRequest request) { + requireWritableReadCommittedOwnerTransaction(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where( + VERSION_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(VERSION_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(VERSION_CANONICAL_VERSION_ID.eq(request.canonicalVersionId())) + .and(VERSION_INTAKE_REQUEST_ID.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (version == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an exact retained V27 authored-Version identity"); + } + Record intake = + dsl.selectFrom(SOURCE_INTAKE) + .where( + INTAKE_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(INTAKE_REQUEST.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (intake == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the exact retained authored-source intake"); + } + Record owner = + dsl.selectFrom(FENCE_OWNER) + .where( + OWNER_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(OWNER_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(OWNER_VERSION_ID.eq(required(version, VERSION_LOCAL_VERSION_KEY)))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an existing V25 shared publication-fence owner row"); + } + String ownerFreezePhase = owner.get(OWNER_FREEZE_PHASE, String.class); + OwnerProvenance provenance = toProvenance(version, ownerFreezePhase); + requireExactIntake(intake, request, provenance); + if (!Objects.equals(owner.get(OWNER_LOCAL_TENANT_KEY), provenance.localTenantKey()) + || !RETAINED_FENCE_PHASES.contains(ownerFreezePhase) + || !request.publicationFence().equals(owner.get(OWNER_CURRENT_FENCE, UUID.class))) { + throw new SnapshotConflictException( + "World graph capture requires the exact retained V25 owner binding"); + } + + Record attempt = + dsl.selectFrom(FENCE_ATTEMPT) + .where( + ATTEMPT_FENCE + .eq(request.publicationFence()) + .and(ATTEMPT_TARGET_NAMESPACE.eq(request.targetNamespace())) + .and(ATTEMPT_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(ATTEMPT_LOCAL_TENANT_KEY.eq(provenance.localTenantKey())) + .and(ATTEMPT_VERSION_ID.eq(provenance.localVersionKey()))) + .forShare() + .fetchOne(); + if (attempt == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the immutable V25 publication attempt"); + } + requireExactAttempt(attempt, request, provenance); + return provenance; + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot findByFence(UUID publicationFence) { + Record row = + dsl.selectFrom(SNAPSHOT) + .where(PUBLICATION_FENCE.eq(Objects.requireNonNull(publicationFence))) + .fetchOne(); + return row == null ? null : toSnapshot(row); + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot insertAndReadback(WorldAuthoredGraphSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + int inserted = + dsl.insertInto(SNAPSHOT) + .set(SNAPSHOT_ID, snapshot.snapshotId()) + .set(CAPTURE_REQUEST_DIGEST, snapshot.captureRequestDigest()) + .set(PUBLICATION_FENCE, snapshot.publicationFence()) + .set(TARGET_NAMESPACE, snapshot.targetNamespace()) + .set(CANONICAL_TENANT_ID, snapshot.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, snapshot.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, snapshot.versionIdentityOperationId()) + .set(WORLD_SLUG, snapshot.worldSlug()) + .set(GAME_DESIGN_VERSION_ID, snapshot.gameDesignVersionId()) + .set(LOCAL_VERSION_KEY, snapshot.localVersionKey()) + .set(LOCAL_TENANT_KEY, snapshot.localTenantKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, snapshot.ownerBindingSchemaVersion()) + .set(INTAKE_OPERATION_ID, snapshot.intakeOperationId()) + .set(INTAKE_REQUEST_ID, snapshot.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, snapshot.intakeRequestDigest()) + .set(SOURCE_OPERATION_ID, snapshot.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, snapshot.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, snapshot.intakeReceiptDigest()) + .set(PUBLICATION_REQUEST_ID, snapshot.publicationRequestId()) + .set(REQUEST_DIGEST, snapshot.requestDigest()) + .set(VERSION_STATE_EPOCH, snapshot.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, snapshot.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, snapshot.appliedCommitId()) + .set(CONTENT_DIGEST, snapshot.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, snapshot.digestSchemaVersion()) + .set(SUPPLIED_TUPLES_JSON, snapshot.suppliedOwnedAffectedTuplesJson()) + .set(OWNER_REVISION_EVIDENCE_JSON, snapshot.ownerRevisionEvidenceJson()) + .set(OWNER_COMMIT_PROOF_STATUS, CAPTURED_UNVERIFIED) + .set(GRAPH_BYTES, snapshot.graphBytes()) + .set(GRAPH_SHA256, snapshot.graphSha256()) + .execute(); + if (inserted != 1) { + throw new SnapshotConflictException("World authored graph snapshot was not inserted"); + } + Record row = dsl.selectFrom(SNAPSHOT).where(SNAPSHOT_ID.eq(snapshot.snapshotId())).fetchOne(); + if (row == null) { + throw new SnapshotConflictException( + "World authored graph snapshot disappeared before immutable readback"); + } + WorldAuthoredGraphSnapshot stored = toSnapshot(row); + requireSameSnapshot(snapshot, stored); + return stored; + } + + public void requireSameRequest( + WorldAuthoredGraphSnapshot snapshot, + CaptureRequest request, + OwnerProvenance provenance, + String captureRequestDigest, + String tuplesJson) { + if (!snapshot.targetNamespace().equals(request.targetNamespace()) + || !snapshot.canonicalTenantId().equals(request.canonicalTenantId()) + || !snapshot.canonicalVersionId().equals(request.canonicalVersionId()) + || !snapshot.versionIdentityOperationId().equals(provenance.versionIdentityOperationId()) + || !snapshot.worldSlug().equals(provenance.worldSlug()) + || snapshot.gameDesignVersionId() != provenance.gameDesignVersionId() + || snapshot.localVersionKey() != provenance.localVersionKey() + || snapshot.localTenantKey() != provenance.localTenantKey() + || snapshot.ownerBindingSchemaVersion() != 1 + || !snapshot.intakeOperationId().equals(provenance.intakeOperationId()) + || !snapshot.intakeRequestId().equals(request.intakeRequestId()) + || !snapshot.intakeRequestDigest().equals(provenance.intakeRequestDigest()) + || !snapshot.sourceOperationId().equals(provenance.sourceOperationId()) + || !snapshot.sourceEvidenceDigest().equals(provenance.sourceEvidenceDigest()) + || !snapshot.intakeReceiptDigest().equals(provenance.intakeReceiptDigest()) + || !snapshot.publicationFence().equals(request.publicationFence()) + || !snapshot.publicationRequestId().equals(request.publicationRequestId()) + || !snapshot.requestDigest().equals(request.requestDigest()) + || snapshot.versionStateEpoch() != request.versionStateEpoch() + || !snapshot.publishWorkflowId().equals(request.publishWorkflowId()) + || !snapshot.appliedCommitId().equals(request.appliedCommitId()) + || !snapshot.contentDigest().equals(request.contentDigest()) + || snapshot.digestSchemaVersion() != request.digestSchemaVersion() + || !snapshot.captureRequestDigest().equals(captureRequestDigest) + || !snapshot.suppliedOwnedAffectedTuplesJson().equals(tuplesJson)) { + throw new SnapshotConflictException( + "World graph capture identity was reused with changed source or request binding"); + } + verifyGraphHash(snapshot); + } + + private OwnerProvenance toProvenance(Record version, String ownerFreezePhase) { + return new OwnerProvenance( + required(version, VERSION_OPERATION_ID), + required(version, VERSION_TARGET_NAMESPACE), + required(version, VERSION_CANONICAL_TENANT_ID), + required(version, VERSION_CANONICAL_VERSION_ID), + required(version, VERSION_WORLD_SLUG), + required(version, VERSION_GAME_DESIGN_VERSION_ID), + required(version, VERSION_LOCAL_VERSION_KEY), + required(version, VERSION_LOCAL_TENANT_KEY), + required(version, VERSION_INTAKE_OPERATION_ID), + required(version, VERSION_INTAKE_REQUEST_ID), + required(version, VERSION_INTAKE_REQUEST_DIGEST), + required(version, VERSION_SOURCE_OPERATION_ID), + required(version, VERSION_SOURCE_EVIDENCE_DIGEST), + required(version, VERSION_INTAKE_RECEIPT_DIGEST), + ownerFreezePhase); + } + + private void requireExactIntake( + Record intake, CaptureRequest request, OwnerProvenance provenance) { + if (!request.targetNamespace().equals(intake.get(INTAKE_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(intake.get(INTAKE_CANONICAL_TENANT_ID, UUID.class)) + || !request.intakeRequestId().equals(intake.get(INTAKE_REQUEST, UUID.class)) + || !provenance.intakeOperationId().equals(intake.get(INTAKE_OPERATION, UUID.class)) + || !provenance.intakeRequestDigest().equals(intake.get("request_digest", String.class)) + || !Objects.equals( + provenance.localTenantKey(), intake.get(INTAKE_LOCAL_TENANT_KEY, Long.class)) + || !provenance + .sourceOperationId() + .equals(intake.get(INTAKE_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(intake.get(INTAKE_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance.intakeReceiptDigest().equals(intake.get(INTAKE_RECEIPT, String.class)) + || !provenance.worldSlug().equals(intake.get(INTAKE_WORLD_SLUG, String.class))) { + throw new SnapshotConflictException( + "World Version provenance differs from its exact authored-source intake"); + } + } + + private void requireExactAttempt( + Record attempt, CaptureRequest request, OwnerProvenance provenance) { + if (!request.publicationFence().equals(attempt.get(ATTEMPT_FENCE, UUID.class)) + || !request.targetNamespace().equals(attempt.get(ATTEMPT_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(attempt.get(ATTEMPT_CANONICAL_TENANT_ID, UUID.class)) + || !Objects.equals( + provenance.localTenantKey(), attempt.get(ATTEMPT_LOCAL_TENANT_KEY, Long.class)) + || !Objects.equals( + provenance.localVersionKey(), attempt.get(ATTEMPT_VERSION_ID, Long.class)) + || !Short.valueOf((short) 1) + .equals(attempt.get(ATTEMPT_OWNER_BINDING_SCHEMA_VERSION, Short.class)) + || !request + .canonicalVersionId() + .equals(attempt.get(ATTEMPT_CANONICAL_VERSION_ID, UUID.class)) + || !provenance + .versionIdentityOperationId() + .equals(attempt.get(ATTEMPT_VERSION_IDENTITY_OPERATION_ID, UUID.class)) + || !Objects.equals( + provenance.gameDesignVersionId(), + attempt.get(ATTEMPT_GAME_DESIGN_VERSION_ID, Long.class)) + || !provenance + .intakeOperationId() + .equals(attempt.get(ATTEMPT_INTAKE_OPERATION_ID, UUID.class)) + || !request.intakeRequestId().equals(attempt.get(ATTEMPT_INTAKE_REQUEST_ID, UUID.class)) + || !provenance + .intakeRequestDigest() + .equals(attempt.get(ATTEMPT_INTAKE_REQUEST_DIGEST, String.class)) + || !provenance + .sourceOperationId() + .equals(attempt.get(ATTEMPT_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(attempt.get(ATTEMPT_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance + .intakeReceiptDigest() + .equals(attempt.get(ATTEMPT_INTAKE_RECEIPT_DIGEST, String.class)) + || !request + .publicationRequestId() + .equals(attempt.get(ATTEMPT_PUBLICATION_REQUEST_ID, String.class)) + || !request.requestDigest().equals(attempt.get(ATTEMPT_REQUEST_DIGEST, String.class)) + || request.versionStateEpoch() != attempt.get(ATTEMPT_VERSION_STATE_EPOCH, Long.class) + || !request + .publishWorkflowId() + .equals(attempt.get(ATTEMPT_PUBLISH_WORKFLOW_ID, String.class)) + || !request.appliedCommitId().equals(attempt.get(ATTEMPT_APPLIED_COMMIT_ID, String.class)) + || !request.contentDigest().equals(attempt.get(ATTEMPT_CONTENT_DIGEST, String.class)) + || request.digestSchemaVersion() + != attempt.get(ATTEMPT_DIGEST_SCHEMA_VERSION, Integer.class)) { + throw new SnapshotConflictException( + "World graph capture differs from the complete immutable V25 freeze attempt"); + } + } + + private WorldAuthoredGraphSnapshot toSnapshot(Record row) { + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + required(row, SNAPSHOT_ID), + required(row, TARGET_NAMESPACE), + required(row, CANONICAL_TENANT_ID), + required(row, CANONICAL_VERSION_ID), + required(row, VERSION_IDENTITY_OPERATION_ID), + required(row, WORLD_SLUG), + required(row, GAME_DESIGN_VERSION_ID), + required(row, LOCAL_VERSION_KEY), + required(row, LOCAL_TENANT_KEY), + required(row, OWNER_BINDING_SCHEMA_VERSION), + required(row, INTAKE_OPERATION_ID), + required(row, INTAKE_REQUEST_ID), + required(row, INTAKE_REQUEST_DIGEST), + required(row, SOURCE_OPERATION_ID), + required(row, SOURCE_EVIDENCE_DIGEST), + required(row, INTAKE_RECEIPT_DIGEST), + required(row, PUBLICATION_FENCE), + required(row, PUBLICATION_REQUEST_ID), + required(row, REQUEST_DIGEST), + required(row, VERSION_STATE_EPOCH), + required(row, PUBLISH_WORKFLOW_ID), + required(row, APPLIED_COMMIT_ID), + required(row, CONTENT_DIGEST), + required(row, DIGEST_SCHEMA_VERSION), + required(row, CAPTURE_REQUEST_DIGEST), + required(row, SUPPLIED_TUPLES_JSON), + required(row, OWNER_REVISION_EVIDENCE_JSON), + required(row, GRAPH_BYTES), + required(row, GRAPH_SHA256), + parseProofStatus(required(row, OWNER_COMMIT_PROOF_STATUS))); + verifyGraphHash(snapshot); + return snapshot; + } + + private OwnerCommitProofStatus parseProofStatus(String value) { + if (!CAPTURED_UNVERIFIED.equals(value)) { + throw new SnapshotConflictException("Unsupported World owner commit proof status"); + } + return OwnerCommitProofStatus.CAPTURED_UNVERIFIED; + } + + private void requireSameSnapshot( + WorldAuthoredGraphSnapshot expected, WorldAuthoredGraphSnapshot stored) { + if (!expected.snapshotId().equals(stored.snapshotId()) + || !expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.canonicalVersionId().equals(stored.canonicalVersionId()) + || !expected.versionIdentityOperationId().equals(stored.versionIdentityOperationId()) + || !expected.worldSlug().equals(stored.worldSlug()) + || expected.gameDesignVersionId() != stored.gameDesignVersionId() + || expected.localVersionKey() != stored.localVersionKey() + || expected.localTenantKey() != stored.localTenantKey() + || expected.ownerBindingSchemaVersion() != stored.ownerBindingSchemaVersion() + || !expected.intakeOperationId().equals(stored.intakeOperationId()) + || !expected.intakeRequestId().equals(stored.intakeRequestId()) + || !expected.intakeRequestDigest().equals(stored.intakeRequestDigest()) + || !expected.sourceOperationId().equals(stored.sourceOperationId()) + || !expected.sourceEvidenceDigest().equals(stored.sourceEvidenceDigest()) + || !expected.intakeReceiptDigest().equals(stored.intakeReceiptDigest()) + || !expected.publicationFence().equals(stored.publicationFence()) + || !expected.publicationRequestId().equals(stored.publicationRequestId()) + || !expected.requestDigest().equals(stored.requestDigest()) + || expected.versionStateEpoch() != stored.versionStateEpoch() + || !expected.publishWorkflowId().equals(stored.publishWorkflowId()) + || !expected.appliedCommitId().equals(stored.appliedCommitId()) + || !expected.contentDigest().equals(stored.contentDigest()) + || expected.digestSchemaVersion() != stored.digestSchemaVersion() + || !expected.captureRequestDigest().equals(stored.captureRequestDigest()) + || !expected + .suppliedOwnedAffectedTuplesJson() + .equals(stored.suppliedOwnedAffectedTuplesJson()) + || !expected.ownerRevisionEvidenceJson().equals(stored.ownerRevisionEvidenceJson()) + || !Arrays.equals(expected.graphBytes(), stored.graphBytes()) + || !expected.graphSha256().equals(stored.graphSha256()) + || expected.ownerCommitProofStatus() != stored.ownerCommitProofStatus()) { + throw new SnapshotConflictException( + "World graph snapshot differs from its immutable committed readback"); + } + } + + private void verifyGraphHash(WorldAuthoredGraphSnapshot snapshot) { + if (!WorldAuthoredGraphSnapshotCapture.sha256(snapshot.graphBytes()) + .equals(snapshot.graphSha256())) { + throw new SnapshotConflictException( + "World authored graph snapshot bytes failed their stored SHA-256 readback"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field); + if (value == null) { + throw new SnapshotConflictException( + "World graph snapshot is missing required " + field.getName()); + } + return value; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + public record OwnerProvenance( + UUID versionIdentityOperationId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String ownerFreezePhase) {} + + public static class SnapshotConflictException extends IllegalStateException { + public SnapshotConflictException(String message) { + super(message); + } + } + + public static class MissingOwnerHistoryException extends IllegalStateException { + public MissingOwnerHistoryException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java index 24b0f3ba96..471b6a5801 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java @@ -11,11 +11,15 @@ public record WorldDesignPublicationFenceEvidence( String targetNamespace, UUID canonicalTenantId, - long versionId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, UUID intakeRequestId, UUID intakeOperationId, + String intakeRequestDigest, UUID sourceOperationId, String sourceEvidenceDigest, + String intakeReceiptDigest, String publicationRequestId, String requestDigest, long versionStateEpoch, @@ -33,15 +37,19 @@ public record WorldDesignPublicationFenceEvidence( new OwnerBinding( targetNamespace, canonicalTenantId, - versionId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, intakeRequestId, intakeOperationId, + intakeRequestDigest, sourceOperationId, - sourceEvidenceDigest); + sourceEvidenceDigest, + intakeReceiptDigest); requirePositive(versionStateEpoch, "versionStateEpoch"); PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.full( - canonicalTenantId.toString(), Long.toString(versionId), publicationRequestId); + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { throw new IllegalArgumentException("requestDigest must be 64 lowercase hexadecimal digits"); } @@ -56,11 +64,15 @@ public OwnerBinding ownerBinding() { return new OwnerBinding( targetNamespace, canonicalTenantId, - versionId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, intakeRequestId, intakeOperationId, + intakeRequestDigest, sourceOperationId, - sourceEvidenceDigest); + sourceEvidenceDigest, + intakeReceiptDigest); } /** @@ -70,24 +82,29 @@ public OwnerBinding ownerBinding() { public record OwnerBinding( String targetNamespace, UUID canonicalTenantId, - long versionId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, UUID intakeRequestId, UUID intakeOperationId, + String intakeRequestDigest, UUID sourceOperationId, - String sourceEvidenceDigest) { + String sourceEvidenceDigest, + String intakeReceiptDigest) { public OwnerBinding { if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); } requireNonNil(canonicalTenantId, "canonicalTenantId"); - requirePositive(versionId, "versionId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); requireNonNil(intakeRequestId, "intakeRequestId"); requireNonNil(intakeOperationId, "intakeOperationId"); + requireDigest(intakeRequestDigest, "intakeRequestDigest"); requireNonNil(sourceOperationId, "sourceOperationId"); - if (sourceEvidenceDigest == null || !SOURCE_DIGEST.matcher(sourceEvidenceDigest).matches()) { - throw new IllegalArgumentException( - "sourceEvidenceDigest must be a canonical prefixed SHA-256 digest"); - } + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + requireDigest(intakeReceiptDigest, "intakeReceiptDigest"); } } @@ -97,7 +114,7 @@ public record OwnerBinding( */ public PublicationDigestRequestBinding publicationBinding() { return PublicationDigestRequestBinding.full( - canonicalTenantId.toString(), Long.toString(versionId), publicationRequestId); + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); } /** Owner-local complete digest checkpoint captured only after the shared version lock is held. */ @@ -157,4 +174,10 @@ private static void requireNonNil(UUID value, String label) { throw new IllegalArgumentException(label + " must be a non-nil UUID"); } } + + private static void requireDigest(String value, String label) { + if (value == null || !SOURCE_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index 9bc4746db0..259f85bb16 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -34,6 +34,8 @@ public class WorldDesignPublicationFenceRepository { private static final Table OWNER = DSL.table(DSL.name("world_design_publication_fence_owner")); private static final Table ATTEMPT = DSL.table(DSL.name("world_design_publication_fence_attempt")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); private static final Field TARGET_NAMESPACE = DSL.field(DSL.name("target_namespace"), String.class); private static final Field CANONICAL_TENANT_ID = @@ -41,6 +43,30 @@ public class WorldDesignPublicationFenceRepository { private static final Field LOCAL_TENANT_KEY = DSL.field(DSL.name("local_tenant_key"), Long.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), Long.class); + private static final Field VERSION_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); private static final Field INTAKE_OPERATION_ID = DSL.field(DSL.name("intake_operation_id"), UUID.class); private static final Field INTAKE_REQUEST_ID = @@ -72,6 +98,16 @@ public class WorldDesignPublicationFenceRepository { DSL.field(DSL.name("content_digest"), String.class); private static final Field DIGEST_SCHEMA_VERSION = DSL.field(DSL.name("digest_schema_version"), Integer.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + DSL.field(DSL.name("owner_binding_schema_version"), Short.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + DSL.field(DSL.name("version_identity_operation_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); private final DSLContext dsl; private final WorldAuthoredSourceIntakeRepository intakeRepository; @@ -94,9 +130,9 @@ public WorldDesignPublicationFenceRepository( @Transactional(propagation = Propagation.MANDATORY) public void lockOpen(OwnerBinding binding) { requireWritableReadCommittedOwnerTransaction(); - ResolvedIntake intake = resolveCommittedIntake(binding); - Record owner = createAndLockOwner(binding, intake); - requireMatchingOwnerBinding(owner, binding, intake); + ResolvedVersion resolvedVersion = resolveVersion(binding); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); if (!OPEN.equals(owner.get(OWNER_FREEZE_PHASE, String.class))) { throw new ConflictException("World version is not open for an ordinary Draft mutation"); } @@ -119,9 +155,10 @@ public FrozenAttempt claimFreeze( requireWritableReadCommittedOwnerTransaction(); Objects.requireNonNull(checkpointSupplier, "checkpointSupplier"); OwnerBinding binding = evidence.ownerBinding(); - ResolvedIntake intake = resolveCommittedIntake(binding); - Record owner = createAndLockOwner(binding, intake); - requireMatchingOwnerBinding(owner, binding, intake); + ResolvedVersion resolvedVersion = resolveVersion(binding); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); String phase = owner.get(OWNER_FREEZE_PHASE, String.class); UUID currentFence = owner.get(CURRENT_PUBLICATION_FENCE, UUID.class); @@ -140,7 +177,7 @@ public FrozenAttempt claimFreeze( throw new ConflictException( "World version cannot start a publication freeze in its current phase"); } - if (findAttemptByRequest(evidence) != null) { + if (findAttemptByRequest(evidence, resolvedVersion.localVersionKey()) != null) { throw new ConflictException("World publication request already has an immutable attempt"); } @@ -148,7 +185,7 @@ public FrozenAttempt claimFreeze( Objects.requireNonNull( checkpointSupplier.get(), "checkpointSupplier returned no complete World checkpoint"); UUID publicationFence = newNonNilUuid(); - int inserted = insertAttempt(evidence, intake, publicationFence, checkpoint); + int inserted = insertAttempt(evidence, resolvedVersion, publicationFence, checkpoint); if (inserted != 1) { throw new ConflictException("World publication attempt was not inserted"); } @@ -161,7 +198,7 @@ public FrozenAttempt claimFreeze( TARGET_NAMESPACE .eq(evidence.targetNamespace()) .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) - .and(VERSION_ID.eq(evidence.versionId())) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey())) .and(OWNER_FREEZE_PHASE.eq(OPEN)) .and(CURRENT_PUBLICATION_FENCE.isNull())) .execute(); @@ -180,8 +217,9 @@ public Optional readAttempt(WorldDesignPublicationFenceEvidence e if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException("World publication attempt read requires a committed read"); } - resolveCommittedIntake(evidence.ownerBinding()); - FrozenAttempt stored = findAttemptByRequest(evidence); + ResolvedVersion resolvedVersion = resolveVersion(evidence.ownerBinding()); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + FrozenAttempt stored = findAttemptByRequest(evidence, resolvedVersion.localVersionKey()); if (stored == null) { return Optional.empty(); } @@ -189,7 +227,7 @@ public Optional readAttempt(WorldDesignPublicationFenceEvidence e return Optional.of(stored); } - private ResolvedIntake resolveCommittedIntake(OwnerBinding binding) { + private ResolvedVersion resolveVersion(OwnerBinding binding) { Objects.requireNonNull(binding, "binding"); WorldAuthoredSourceIntakeReceipt receipt = intakeRepository @@ -198,25 +236,81 @@ private ResolvedIntake resolveCommittedIntake(OwnerBinding binding) { () -> new MissingIntakeException( "World publication fence requires an already committed authored-source intake")); + requireExactIntake(binding, receipt); + + Record identity = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(binding.versionIdentityOperationId())) + .forShare() + .fetchOne(); + if (identity == null) { + throw new MissingVersionIdentityException( + "World publication fence requires an exact retained V27 authored-Version identity"); + } + requireExactVersionIdentity(identity, binding, receipt); + Long localVersionKey = identity.get(VERSION_LOCAL_VERSION_KEY, Long.class); + if (localVersionKey == null || localVersionKey <= 0L) { + throw new ConflictException("World Version identity has no valid private local Version key"); + } + return new ResolvedVersion(binding, receipt, localVersionKey); + } + + private void requireExactIntake(OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { if (!binding.targetNamespace().equals(receipt.targetNamespace()) || !binding.canonicalTenantId().equals(receipt.canonicalTenantId()) || !binding.intakeRequestId().equals(receipt.intakeRequestId()) || !binding.intakeOperationId().equals(receipt.operationId()) + || !binding.intakeRequestDigest().equals(receipt.requestDigest()) || !binding.sourceOperationId().equals(receipt.sourceOperationId()) - || !binding.sourceEvidenceDigest().equals(receipt.sourceEvidenceDigest())) { + || !binding.sourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || !binding.intakeReceiptDigest().equals(receipt.receiptDigest())) { throw new ConflictException( "World publication request differs from the complete committed authored-source intake"); } - return new ResolvedIntake(receipt); } - private Record createAndLockOwner(OwnerBinding binding, ResolvedIntake intake) { - WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + private void requireExactVersionIdentity( + Record identity, OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { + if (!Objects.equals( + identity.get(VERSION_OPERATION_ID, UUID.class), binding.versionIdentityOperationId()) + || !Objects.equals(identity.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals( + identity.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals( + identity.get(VERSION_CANONICAL_VERSION_ID, UUID.class), binding.canonicalVersionId()) + || !Objects.equals( + identity.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), binding.gameDesignVersionId()) + || !Objects.equals(identity.get(VERSION_WORLD_SLUG, String.class), receipt.worldSlug()) + || !Objects.equals( + identity.get(VERSION_INTAKE_OPERATION_ID, UUID.class), binding.intakeOperationId()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_ID, UUID.class), binding.intakeRequestId()) + || !Objects.equals( + identity.get(VERSION_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), + binding.intakeRequestDigest()) + || !Objects.equals( + identity.get(VERSION_SOURCE_OPERATION_ID, UUID.class), binding.sourceOperationId()) + || !Objects.equals( + identity.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + binding.sourceEvidenceDigest()) + || !Objects.equals( + identity.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), + binding.intakeReceiptDigest())) { + throw new ConflictException( + "World publication request differs from the exact V27 Version and intake binding"); + } + } + + private Record createAndLockOwner(ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); dsl.insertInto(OWNER) .set(TARGET_NAMESPACE, binding.targetNamespace()) .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) - .set(VERSION_ID, binding.versionId()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) .set(OWNER_FREEZE_PHASE, OPEN) .onConflictDoNothing() .execute(); @@ -227,7 +321,7 @@ private Record createAndLockOwner(OwnerBinding binding, ResolvedIntake intake) { TARGET_NAMESPACE .eq(binding.targetNamespace()) .and(CANONICAL_TENANT_ID.eq(binding.canonicalTenantId())) - .and(VERSION_ID.eq(binding.versionId()))) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey()))) .forUpdate() .fetchOne(); if (owner == null) { @@ -236,13 +330,13 @@ private Record createAndLockOwner(OwnerBinding binding, ResolvedIntake intake) { return owner; } - private void requireMatchingOwnerBinding( - Record owner, OwnerBinding binding, ResolvedIntake intake) { - WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + private void requireMatchingOwnerBinding(Record owner, ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); if (!Objects.equals(owner.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) || !Objects.equals(owner.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) || !Objects.equals(owner.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) - || !Objects.equals(owner.get(VERSION_ID, Long.class), binding.versionId())) { + || !Objects.equals(owner.get(VERSION_ID, Long.class), resolvedVersion.localVersionKey())) { throw new ConflictException( "World version owner row is bound to a different canonical tenant association"); } @@ -250,18 +344,24 @@ private void requireMatchingOwnerBinding( private int insertAttempt( WorldDesignPublicationFenceEvidence evidence, - ResolvedIntake intake, + ResolvedVersion resolvedVersion, UUID publicationFence, Checkpoint checkpoint) { - WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); return dsl.insertInto(ATTEMPT) .set(PUBLICATION_FENCE, publicationFence) - .set(TARGET_NAMESPACE, evidence.targetNamespace()) - .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) - .set(VERSION_ID, evidence.versionId()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, (short) 1) + .set(CANONICAL_VERSION_ID, binding.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, binding.versionIdentityOperationId()) + .set(GAME_DESIGN_VERSION_ID, binding.gameDesignVersionId()) .set(INTAKE_OPERATION_ID, receipt.operationId()) .set(INTAKE_REQUEST_ID, receipt.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, receipt.requestDigest()) .set(SOURCE_OPERATION_ID, receipt.sourceOperationId()) .set(SOURCE_EVIDENCE_DIGEST, receipt.sourceEvidenceDigest()) .set(INTAKE_RECEIPT_DIGEST, receipt.receiptDigest()) @@ -281,29 +381,58 @@ private FrozenAttempt findAttemptByFence(UUID publicationFence) { return record == null ? null : toFrozenAttempt(record); } - private FrozenAttempt findAttemptByRequest(WorldDesignPublicationFenceEvidence evidence) { + private FrozenAttempt findAttemptByRequest( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { Record record = dsl.selectFrom(ATTEMPT) .where( TARGET_NAMESPACE .eq(evidence.targetNamespace()) .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) - .and(VERSION_ID.eq(evidence.versionId())) + .and(VERSION_ID.eq(localVersionKey)) .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) .fetchOne(); return record == null ? null : toFrozenAttempt(record); } + private void rejectLegacyAttempt( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { + Record legacyCandidate = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(localVersionKey)) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + if (legacyCandidate != null + && !Short.valueOf((short) 1) + .equals(legacyCandidate.get(OWNER_BINDING_SCHEMA_VERSION, Short.class))) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } + } + private FrozenAttempt toFrozenAttempt(Record record) { + Short ownerBindingSchemaVersion = record.get(OWNER_BINDING_SCHEMA_VERSION, Short.class); + if (!Short.valueOf((short) 1).equals(ownerBindingSchemaVersion)) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } WorldDesignPublicationFenceEvidence request = new WorldDesignPublicationFenceEvidence( record.get(TARGET_NAMESPACE), record.get(CANONICAL_TENANT_ID), - record.get(VERSION_ID), + record.get(CANONICAL_VERSION_ID), + record.get(VERSION_IDENTITY_OPERATION_ID), + record.get(GAME_DESIGN_VERSION_ID), record.get(INTAKE_REQUEST_ID), record.get(INTAKE_OPERATION_ID), + record.get(INTAKE_REQUEST_DIGEST), record.get(SOURCE_OPERATION_ID), record.get(SOURCE_EVIDENCE_DIGEST), + record.get(INTAKE_RECEIPT_DIGEST), record.get(PUBLICATION_REQUEST_ID), record.get(REQUEST_DIGEST), record.get(VERSION_STATE_EPOCH), @@ -358,10 +487,11 @@ private UUID newNonNilUuid() { return value; } - private record ResolvedIntake(WorldAuthoredSourceIntakeReceipt receipt) {} + private record ResolvedVersion( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) {} /** Exact input conflicts fail closed without changing either owner or attempt history. */ - public static final class ConflictException extends IllegalStateException { + public static class ConflictException extends IllegalStateException { public ConflictException(String message) { super(message); } @@ -373,4 +503,11 @@ public MissingIntakeException(String message) { super(message); } } + + /** No owner state may be created for a missing V27 source-qualified Version identity. */ + public static final class MissingVersionIdentityException extends ConflictException { + public MissingVersionIdentityException(String message) { + super(message); + } + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java new file mode 100644 index 0000000000..f74180d733 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; + +/** + * Pure, typed validation of the World-owned region-upsert subset of a complete Draft commit. + * + *

This validates only the supplied owner binding and World revision subset. It does not + * authenticate the source evidence, authorize a write, consult storage, or represent an applied + * owner result. + */ +public final class WorldDraftRegionCommitPlan { + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final JsonFormat.Parser PAYLOAD_PARSER = JsonFormat.parser(); + + /** + * One decoded World revision, retaining its position in the enclosing canonical revision list. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value messages.") + public record RegionRevision( + String revisionOrder, UUID revisionId, WorldDesignMutationRevision mutation) { + public RegionRevision { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(mutation, "mutation"); + } + } + + private final DraftCommitBinding binding; + private final WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding; + private final List regionRevisions; + + private WorldDraftRegionCommitPlan( + DraftCommitBinding binding, + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding, + List regionRevisions) { + this.binding = binding; + this.ownerBinding = ownerBinding; + this.regionRevisions = List.copyOf(regionRevisions); + } + + /** + * Validates the World-owned ordered revision subset against the exact supplied owner scope. + * + *

The {@code ownerBinding} carries caller-supplied source evidence; this method checks that + * its canonical tenant, Version, and Game Design Version selector match the shared binding, but + * does not authenticate that evidence. + */ + public static WorldDraftRegionCommitPlan create( + DraftCommitBinding binding, WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + validateTarget(binding.target(), ownerBinding); + + List decoded = new ArrayList<>(); + List expectedWorldUnits = new ArrayList<>(); + Set worldRevisionIds = new HashSet<>(); + Set regionIds = new HashSet<>(); + + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + if (!worldRevisionIds.add(revision.revisionId())) { + throw invalid("World subset contains a duplicate revision identity"); + } + + WorldDesignMutationRevision mutation = parseRevision(revision.payload()); + validateRevisionIdentity(binding.commitId(), revision, mutation); + validateSupportedRegionUpsert(mutation); + + String regionId = mutation.getAggregateId(); + parsePositiveId(regionId, "aggregate_id"); + if (!regionId.equals(mutation.getScopeId())) { + throw invalid("REGION_SUBTREE scope_id must exactly match aggregate_id"); + } + if (!regionIds.add(regionId)) { + throw invalid("World subset contains duplicate region mutations"); + } + + long aggregateEpoch = validateEpoch(mutation.getExpectedDraftRevisionEpoch(), "aggregate"); + long scopeEpoch = validateEpoch(mutation.getExpectedDraftScopeRevisionEpoch(), "scope"); + expectedWorldUnits.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId, + "AGGREGATE", + regionId, + Long.toString(aggregateEpoch))); + expectedWorldUnits.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId, + "REGION_SUBTREE", + regionId, + Long.toString(scopeEpoch))); + decoded.add(new RegionRevision(revision.revisionOrder(), revision.revisionId(), mutation)); + } + + if (decoded.isEmpty()) { + throw invalid("Draft commit has no World-owned region revisions"); + } + requireExactWorldUnits(binding.affectedUnits(Owner.WORLD_MANAGEMENT), expectedWorldUnits); + return new WorldDraftRegionCommitPlan(binding, ownerBinding, decoded); + } + + /** Returns the exact immutable enclosing commit binding, including other owners' declarations. */ + public DraftCommitBinding binding() { + return binding; + } + + /** Returns the exact source-qualified World owner scope validated for this plan. */ + public WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return ownerBinding; + } + + /** Returns the decoded World region revisions in their original enclosing revision order. */ + public List regionRevisions() { + return List.copyOf(regionRevisions); + } + + private static void validateTarget( + DraftCommitBinding.TargetProof target, + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + // Compare only the canonical identity and Game Design Version selector present in both + // contracts. The World-local numeric key is not part of either input and must not be inferred + // from the Game Design selector. Remaining source-qualified evidence is retained on the plan + // and must be checked against World's retained identity and intake at its owner boundary. + if (!target.canonicalTenantId().equals(ownerBinding.canonicalTenantId()) + || !target.canonicalVersionId().equals(ownerBinding.canonicalVersionId()) + || target.gameDesignVersionRowId() != ownerBinding.gameDesignVersionId()) { + throw invalid("Draft commit target does not match the supplied World owner binding"); + } + } + + private static WorldDesignMutationRevision parseRevision(String payload) { + WorldDesignMutationRevision.Builder builder = WorldDesignMutationRevision.newBuilder(); + try { + // Unknown JSON fields are rejected by the default parser; accepting them would permit + // unvalidated input to disappear from the owner-specific typed interpretation. + PAYLOAD_PARSER.merge(payload, builder); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalArgumentException( + "World revision payload is not valid typed JSON", exception); + } + return builder.build(); + } + + private static void validateRevisionIdentity( + UUID commitId, + DraftCommitBinding.RevisionPayload revision, + WorldDesignMutationRevision mutation) { + if (!commitId.toString().equals(mutation.getCommitId())) { + throw invalid("World payload commit_id does not match the enclosing commit"); + } + if (!revision.revisionId().toString().equals(mutation.getLogicalRevisionId())) { + throw invalid("World payload logical_revision_id does not match the enclosing revision"); + } + } + + private static void validateSupportedRegionUpsert(WorldDesignMutationRevision mutation) { + if (mutation.getOperation() + != WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT + || mutation.getAggregateType() + != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || mutation.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE + || mutation.getScopeMutationPolicy() + != WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED + || mutation.getPayloadCase() != WorldDesignMutationRevision.PayloadCase.REGION) { + throw invalid( + "World commit plan supports only existing REGION UPSERT with REGION_SUBTREE scope"); + } + if (mutation.getRegion().getName().isBlank()) { + throw invalid("REGION UPSERT requires a nonempty region name"); + } + double spacing = mutation.getRegion().getSpacingMultiplier(); + // The existing World mutation contract treats zero as the default multiplier (1.0). + if (!Double.isFinite(spacing) || spacing < 0.0d) { + throw invalid("REGION UPSERT spacing_multiplier must be finite and nonnegative"); + } + } + + private static long parsePositiveId(String value, String label) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(label + " must be a canonical positive decimal ID"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException(label + " is outside the supported ID range", exception); + } + } + + private static long validateEpoch(long epoch, String label) { + if (epoch < 0L || epoch == Long.MAX_VALUE) { + throw invalid("Expected Draft " + label + " epoch must be nonnegative and advanceable"); + } + return epoch; + } + + private static void requireExactWorldUnits( + List declaredUnits, List expectedUnits) { + if (declaredUnits.size() != expectedUnits.size() + || !new HashSet<>(declaredUnits).equals(new HashSet<>(expectedUnits))) { + throw invalid( + "World affected units must exactly match each REGION aggregate and REGION_SUBTREE fence"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql b/services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql new file mode 100644 index 0000000000..7ce80da733 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql @@ -0,0 +1,329 @@ +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ), + ADD CONSTRAINT uq_world_authored_version_snapshot_attempt_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN owner_binding_schema_version SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN canonical_version_id UUID, + ADD COLUMN version_identity_operation_id UUID, + ADD COLUMN game_design_version_id BIGINT, + ADD COLUMN intake_request_digest VARCHAR(71), + ADD CONSTRAINT ck_world_publication_attempt_owner_binding CHECK ( + (owner_binding_schema_version = 0 + AND canonical_version_id IS NULL + AND version_identity_operation_id IS NULL + AND game_design_version_id IS NULL + AND intake_request_digest IS NULL) + OR + (owner_binding_schema_version = 1 + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id IS NOT NULL + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND intake_request_digest IS NOT NULL + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_world_publication_attempt_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD CONSTRAINT uq_world_publication_snapshot_binding UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ); + +CREATE TABLE world_authored_graph_snapshot ( + snapshot_id UUID NOT NULL, + capture_request_digest VARCHAR(64) NOT NULL, + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + owner_binding_schema_version SMALLINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + supplied_owned_affected_tuples_json TEXT NOT NULL, + owner_revision_evidence_json TEXT NOT NULL, + owner_commit_proof_status VARCHAR(32) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_world_authored_graph_snapshot PRIMARY KEY (snapshot_id), + CONSTRAINT uq_world_authored_graph_snapshot_fence UNIQUE (publication_fence), + CONSTRAINT uq_world_authored_graph_snapshot_request UNIQUE ( + target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id + ), + CONSTRAINT fk_world_authored_graph_snapshot_attempt FOREIGN KEY ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + local_version_key, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ) REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ), + CONSTRAINT fk_world_authored_graph_snapshot_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ), + CONSTRAINT fk_world_authored_graph_snapshot_intake FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version = 2 + ), + CONSTRAINT ck_world_authored_graph_snapshot_ids CHECK ( + snapshot_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_graph_snapshot_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_source_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_request CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND capture_request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + ), + CONSTRAINT ck_world_authored_graph_snapshot_checkpoint CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 + ), + CONSTRAINT ck_world_authored_graph_snapshot_proof CHECK ( + owner_commit_proof_status = 'CAPTURED_UNVERIFIED' + AND octet_length(supplied_owned_affected_tuples_json) > 0 + AND octet_length(owner_revision_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_authored_graph_snapshot_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored graph snapshot history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_authored_graph_snapshot_immutable + BEFORE UPDATE OR DELETE ON world_authored_graph_snapshot + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); + +CREATE TRIGGER trg_world_authored_graph_snapshot_no_truncate + BEFORE TRUNCATE ON world_authored_graph_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java new file mode 100644 index 0000000000..4db6ce6def --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -0,0 +1,770 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import java.util.Objects; +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.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotCapture; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredGraphSnapshotPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final long LARGE_VALUE = 9_007_199_254_740_999L; + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_000_000_001L; + private static final List SYNTHETIC_RETENTION_TABLES = + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_revision_ledger"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository publicationFenceRepository; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshotRepository; + @Autowired private WorldDraftDesignDigestService draftDigestService; + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void exactSnapshotSurvivesRollbackAndConcurrentRetryWithFullGraphReadback() throws Exception { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + captureWithGuardedSessionRole(capture, fixture.request()); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + + CountDownLatch firstCaptured = new CountDownLatch(1); + CountDownLatch allowFirstCommit = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + WorldAuthoredGraphSnapshot snapshot = + captureWithGuardedSessionRole(capture, fixture.request()); + firstCaptured.countDown(); + await(allowFirstCommit); + return snapshot; + })); + assertThat(firstCaptured.await(15, TimeUnit.SECONDS)).isTrue(); + Future second = + executor.submit( + () -> { + secondStarted.countDown(); + return ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request())); + }); + assertThat(secondStarted.await(15, TimeUnit.SECONDS)).isTrue(); + allowFirstCommit.countDown(); + + WorldAuthoredGraphSnapshot firstSnapshot = first.get(20, TimeUnit.SECONDS); + WorldAuthoredGraphSnapshot retrySnapshot = second.get(20, TimeUnit.SECONDS); + assertThat(retrySnapshot.snapshotId()).isEqualTo(firstSnapshot.snapshotId()); + assertThat(retrySnapshot.graphBytes()).containsExactly(firstSnapshot.graphBytes()); + assertThat(retrySnapshot.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + assertThat(retrySnapshot.gameDesignVersionId()).isEqualTo(fixture.gameDesignVersionId()); + assertThat(retrySnapshot.localVersionKey()).isEqualTo(fixture.localVersionKey()); + assertThat(retrySnapshot.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(retrySnapshot.versionIdentityOperationId()) + .isEqualTo(fixture.versionIdentityOperationId()); + String graph = new String(retrySnapshot.graphBytes(), StandardCharsets.UTF_8); + assertThat(graph) + .contains( + "\"regions\"", + "\"zones\"", + "\"rooms\"", + "\"roomExits\"", + "\"generationRules\"", + "\"worldEntitySpawnBindings\"", + Long.toString(LARGE_VALUE)); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + + CaptureRequest changedTuples = + copyRequest( + fixture.request(), + List.of( + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", "ROOM", "8", "ZONE_SUBTREE", "7", "12"))); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, changedTuples))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("changed source or request binding"); + + CaptureRequest changedCommit = + new CaptureRequest( + fixture.request().targetNamespace(), + fixture.request().canonicalTenantId(), + fixture.request().canonicalVersionId(), + fixture.request().intakeRequestId(), + fixture.request().publicationFence(), + fixture.request().publicationRequestId(), + fixture.request().requestDigest(), + fixture.request().versionStateEpoch(), + fixture.request().publishWorkflowId(), + "different-commit", + fixture.request().contentDigest(), + fixture.request().digestSchemaVersion(), + fixture.request().suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, changedCommit))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("complete immutable V25 freeze attempt"); + + CaptureRequest wrongSource = + new CaptureRequest( + NAMESPACE, + fixture.request().canonicalTenantId(), + UUID.randomUUID(), + fixture.request().intakeRequestId(), + fixture.request().publicationFence(), + fixture.request().publicationRequestId(), + fixture.request().requestDigest(), + fixture.request().versionStateEpoch(), + fixture.request().publishWorkflowId(), + fixture.request().appliedCommitId(), + fixture.request().contentDigest(), + fixture.request().digestSchemaVersion(), + fixture.request().suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, wrongSource))) + .isInstanceOf(MissingOwnerHistoryException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_graph_snapshot SET graph_sha256 = ? WHERE snapshot_id = ?", + "b".repeat(64), + firstSnapshot.snapshotId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + WorldAuthoredGraphSnapshot immutableReadback = + ownerTransaction() + .execute( + status -> snapshotRepository.findByFence(fixture.request().publicationFence())); + assertThat(immutableReadback.graphSha256()).isEqualTo(firstSnapshot.graphSha256()); + } finally { + allowFirstCommit.countDown(); + executor.shutdownNow(); + } + } + + @Test + void wrongTenantVersionParentEdgeDeniesCaptureBeforeSnapshotRetention() { + Fixture fixture = fixture(true); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request()))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("zone parent is missing or belongs to another tenant/Version"); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory() { + Fixture fixture = fixture(false); + WorldAuthoredSourceIntakeReceipt intake = fixture.intakeReceipt(); + long ownerCountBefore = ownerCount(intake.canonicalTenantId(), fixture.localVersionKey()); + long attemptCountBefore = attemptCount(intake.canonicalTenantId(), fixture.localVersionKey()); + + String publicationRequestId = "missing-intake-request-digest-" + UUID.randomUUID(); + String workflowId = + PublicationDigestRequestBinding.full( + intake.canonicalTenantId().toString(), + Long.toString(fixture.gameDesignVersionId()), + publicationRequestId) + .derivedWorkflowIdentity(); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt (" + + "publication_fence, target_namespace, canonical_tenant_id, " + + "local_tenant_key, version_id, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, " + + "game_design_version_id, intake_operation_id, intake_request_id, " + + "intake_request_digest, source_operation_id, source_evidence_digest, " + + "intake_receipt_digest, publication_request_id, request_digest, " + + "version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2)", + UUID.randomUUID(), + NAMESPACE, + intake.canonicalTenantId(), + intake.localTenantKey(), + fixture.localVersionKey(), + fixture.request().canonicalVersionId(), + fixture.versionIdentityOperationId(), + fixture.gameDesignVersionId(), + intake.operationId(), + intake.intakeRequestId(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + publicationRequestId, + REQUEST_DIGEST, + fixture.request().versionStateEpoch(), + workflowId, + "unbound-commit", + fixture.request().contentDigest())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + assertThat(ownerCount(intake.canonicalTenantId(), fixture.localVersionKey())) + .isEqualTo(ownerCountBefore); + assertThat(attemptCount(intake.canonicalTenantId(), fixture.localVersionKey())) + .isEqualTo(attemptCountBefore); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup() { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + WorldAuthoredGraphSnapshot retainedSnapshot = + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request())); + List retainedRowsBefore = syntheticRetentionRowCounts(fixture); + + assertThat(retainedRowsBefore).containsExactly(1L, 1L, 1L, 1L, 1L, 1L, 1L); + assertThat(retainedSnapshot.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + assertGuardedSessionReplicationRole(); + dsl.execute( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('legacy bypass attempt', ?, ?, ?)", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + LARGE_VALUE); + return null; + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies(this::assertV24CanonicalKeyDenial); + + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(retainedRowsBefore); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + WorldAuthoredGraphSnapshot readback = + ownerTransaction() + .execute( + status -> snapshotRepository.findByFence(fixture.request().publicationFence())); + assertThat(readback.snapshotId()).isEqualTo(retainedSnapshot.snapshotId()); + assertThat(readback.graphBytes()).containsExactly(retainedSnapshot.graphBytes()); + assertThat(readback.graphSha256()).isEqualTo(retainedSnapshot.graphSha256()); + assertThat(readback.captureRequestDigest()).isEqualTo(retainedSnapshot.captureRequestDigest()); + assertThat(readback.suppliedOwnedAffectedTuplesJson()) + .isEqualTo(retainedSnapshot.suppliedOwnedAffectedTuplesJson()); + assertThat(readback.ownerRevisionEvidenceJson()) + .isEqualTo(retainedSnapshot.ownerRevisionEvidenceJson()); + assertThat(readback.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + } + + private Fixture fixture(boolean wrongRoomParent) { + return ownerTransaction() + .execute( + status -> { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + AuthoredWorldSourceEvidence source = + source(canonicalTenantId, tenantSlug, worldSlug, positiveLong()); + UUID intakeRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.acceptFresh(NAMESPACE, intakeRequestId, source); + long gameDesignVersionId = GAME_DESIGN_VERSION_ID; + UUID canonicalVersion = UUID.randomUUID(); + UUID versionStateReadRequestId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request versionStateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + versionStateReadRequestId, + canonicalTenantId, + worldSlug, + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence versionStateEvidence = + AuthoredWorldVersionStateEvidence.create( + versionStateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + WorldAuthoredVersionIdentityReceipt versionIdentity = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(intake, versionStateEvidence); + long localVersionKey = versionIdentity.localVersionKey(); + + Long wrongParentZoneId = null; + if (wrongRoomParent) { + long legacyTenantId = positiveLong(); + long foreignRegionId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region (name, tenant_id, version_id) " + + "VALUES ('foreign region', ?, 777777) RETURNING id", + legacyTenantId) + .fetchOne(0, Long.class), + "Foreign region insert did not return its generated ID"); + wrongParentZoneId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone (region_id, name, tenant_id, version_id) " + + "VALUES (?, 'foreign zone', ?, 777777) RETURNING id", + foreignRegionId, + legacyTenantId) + .fetchOne(0, Long.class), + "Foreign zone insert did not return its generated ID"); + } + // This synthetic component fixture stipulates owner-applied rows; no authenticated + // canonical World owner producer exists or is proved by this fixture. + SyntheticRows syntheticRows = + seedSyntheticCanonicalRows( + intake.localTenantKey(), localVersionKey, wrongParentZoneId); + assertGuardedSessionReplicationRole(); + WorldDraftDesignDigest digest = + draftDigestService.getDraftDesignDigest( + Long.toString(intake.localTenantKey()), Long.toString(localVersionKey)); + + String publicationRequestId = "request-" + UUID.randomUUID(); + String publishWorkflowId = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), + Long.toString(gameDesignVersionId), + publicationRequestId) + .derivedWorkflowIdentity(); + long versionStateEpoch = 7L; + assertGuardedSessionReplicationRole(); + WorldDesignPublicationFenceEvidence fenceRequest = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + canonicalVersion, + versionIdentity.operationId(), + gameDesignVersionId, + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + publicationRequestId, + REQUEST_DIGEST, + versionStateEpoch, + publishWorkflowId); + FrozenAttempt frozen = + publicationFenceRepository.claimFreeze( + fenceRequest, + () -> + new Checkpoint( + syntheticRows.commitId(), + digest.contentDigest(), + digest.digestSchemaVersion())); + UUID publicationFence = frozen.publicationFence(); + CaptureRequest request = + new CaptureRequest( + NAMESPACE, + canonicalTenantId, + canonicalVersion, + intakeRequestId, + publicationFence, + publicationRequestId, + REQUEST_DIGEST, + versionStateEpoch, + publishWorkflowId, + syntheticRows.commitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + List.of( + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", + "WORLD_GENERATION_SUBTREE", + Long.toString(syntheticRows.regionId()), + "REGION_SUBTREE", + Long.toString(syntheticRows.regionId()), + "1"))); + return new Fixture( + request, + localVersionKey, + gameDesignVersionId, + versionIdentity.operationId(), + intake); + }); + } + + private WorldAuthoredGraphSnapshotCapture captureComponent() { + return new WorldAuthoredGraphSnapshotCapture( + dsl, draftDigestService, snapshotRepository, objectMapper); + } + + private WorldAuthoredGraphSnapshot captureWithGuardedSessionRole( + WorldAuthoredGraphSnapshotCapture capture, CaptureRequest request) { + assertGuardedSessionReplicationRole(); + return capture.capture(request); + } + + private SyntheticRows seedSyntheticCanonicalRows( + long localTenantKey, long localVersionKey, Long wrongParentZoneId) { + String originalRole = currentSessionReplicationRole(); + assertThat(originalRole).isEqualTo("origin"); + Throwable seedFailure = null; + try { + // Bypass V24 triggers only while inserting these synthetic six-family and ledger rows. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + assertThat(currentSessionReplicationRole()).isEqualTo("replica"); + + long regionId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('authored region', ?, ?, ?) RETURNING id", + localTenantKey, + localVersionKey, + LARGE_VALUE) + .fetchOne(0, Long.class), + "Region insert did not return its generated ID"); + long zoneId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone (region_id, name, tenant_id, version_id) " + + "VALUES (?, 'authored zone', ?, ?) RETURNING id", + regionId, + localTenantKey, + localVersionKey) + .fetchOne(0, Long.class), + "Zone insert did not return its generated ID"); + long roomParentZoneId = wrongParentZoneId == null ? zoneId : wrongParentZoneId; + long roomId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO room (zone_id, name, description, tenant_id, version_id) " + + "VALUES (?, 'authored room', NULL, ?, ?) RETURNING id", + roomParentZoneId, + localTenantKey, + localVersionKey) + .fetchOne(0, Long.class), + "Room insert did not return its generated ID"); + dsl.execute( + "INSERT INTO room_exit (tenant_id, version_id, from_room_id, to_room_id, direction, cost) " + + "VALUES (?, ?, ?, ?, 'NORTH', 2)", + localTenantKey, + localVersionKey, + roomId, + roomId); + dsl.execute( + "INSERT INTO generation_rule (tenant_id, version_id, name, scope_type, scope_id, value) " + + "VALUES (?, ?, 'dungeon', 'REGION_SUBTREE', ?, 'seeded')", + localTenantKey, + localVersionKey, + Long.toString(regionId)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding (tenant_id, version_id, room_id, " + + "entity_template_type, entity_template_id, spawn_count, respawn_delay_seconds) " + + "VALUES (?, ?, ?, 'NPC', ?, 2, 30)", + localTenantKey, + localVersionKey, + roomId, + LARGE_VALUE); + String commitId = "commit-" + UUID.randomUUID(); + dsl.execute( + "INSERT INTO world_design_revision_ledger (tenant_id, version_id, commit_id, " + + "revision_id, operation_type, aggregate_type, requested_aggregate_id, " + + "applied_aggregate_id, result, aggregate_epoch_after, scope_epoch_after) " + + "VALUES (?, ?, ?, 'revision-1', 'UPSERT', 'WORLD_GENERATION_SUBTREE', ?, ?, 'APPLIED', 1, 1)", + localTenantKey, + localVersionKey, + commitId, + Long.toString(regionId), + regionId); + return new SyntheticRows(regionId, commitId); + } catch (RuntimeException | Error failure) { + seedFailure = failure; + throw failure; + } finally { + try { + String restoredRole = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT set_config('session_replication_role', ?, true)", originalRole) + .fetchOne(0, String.class), + "PostgreSQL did not return restored session_replication_role"); + assertThat(restoredRole).isEqualTo(originalRole); + assertThat(currentSessionReplicationRole()).isEqualTo(originalRole); + } catch (RuntimeException | Error restoreFailure) { + if (seedFailure == null) { + throw restoreFailure; + } + // A PostgreSQL setup error aborts the transaction, so SET LOCAL will revert on rollback. + // Preserve that original setup error if this explicit restore cannot run in the aborted tx. + seedFailure.addSuppressed(restoreFailure); + } + } + } + + private String currentSessionReplicationRole() { + return Objects.requireNonNull( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class), + "PostgreSQL did not return session_replication_role"); + } + + private void assertGuardedSessionReplicationRole() { + assertThat(currentSessionReplicationRole()).isEqualTo("origin"); + } + + private void assertV24CanonicalKeyDenial(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("is reserved for a canonical authored source"); + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + + private CaptureRequest copyRequest(CaptureRequest request, List tuples) { + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + tuples); + } + + private AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceGameRowId) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String displayName = "Synthetic graph snapshot world"; + String sourceTenantKey = "gd-row-" + sourceGameRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private long snapshotCount(UUID fence) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_authored_graph_snapshot WHERE publication_fence = ?", + fence) + .fetchOne(0, Long.class), + "Snapshot count query returned no value"); + } + + private List syntheticRetentionRowCounts(Fixture fixture) { + return SYNTHETIC_RETENTION_TABLES.stream() + .map( + table -> + Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + table + + " WHERE tenant_id = ? AND version_id = ?", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey()) + .fetchOne(0, Long.class), + table + " count query returned no value")) + .toList(); + } + + private long ownerCount(UUID tenantId, long localVersionKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_owner " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + localVersionKey) + .fetchOne(0, Long.class), + "Owner count query returned no value"); + } + + private long attemptCount(UUID tenantId, long localVersionKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_attempt " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + localVersionKey) + .fetchOne(0, Long.class), + "Attempt count query returned no value"); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("World graph snapshot transaction barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "World graph snapshot transaction was interrupted", exception); + } + } + + private record Fixture( + CaptureRequest request, + long localVersionKey, + long gameDesignVersionId, + UUID versionIdentityOperationId, + WorldAuthoredSourceIntakeReceipt intakeReceipt) {} + + private record SyntheticRows(long regionId, String commitId) {} + + private static final class ForcedRollbackException extends RuntimeException {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java index 57ba1d0322..369aa953bc 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.Objects; import java.util.UUID; @@ -12,9 +13,11 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; @@ -22,6 +25,8 @@ import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; @@ -52,6 +57,8 @@ class WorldDesignPublicationFenceIntegrationTest { private static final String NAMESPACE = "firemud"; private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final long GAME_DESIGN_VERSION_A = 9_000_000_042L; + private static final long GAME_DESIGN_VERSION_B = 9_000_000_043L; private static final Checkpoint SYNTHETIC_CHECKPOINT = new Checkpoint("synthetic-commit-42", "c".repeat(64), 2); @@ -86,7 +93,8 @@ static void configure(DynamicPropertyRegistry registry) { @Test void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); - WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-7", 42, 9L); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-7", GAME_DESIGN_VERSION_A, 9L); assertThatThrownBy( () -> @@ -97,14 +105,33 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { throw new ForcedRollbackException(); })) .isInstanceOf(ForcedRollbackException.class); - assertThat(ownerCount(receipt.canonicalTenantId(), 42)).isZero(); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); FrozenAttempt frozen = ownerTransaction() .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); assertThat(frozen).isNotNull(); assertThat(repository.readAttempt(request)).contains(frozen); - assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + var storedBinding = + dsl.fetchOne( + "SELECT owner_binding_schema_version, version_id, canonical_version_id, " + + "version_identity_operation_id, game_design_version_id, intake_request_digest " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + frozen.publicationFence()); + assertThat(storedBinding).isNotNull(); + assertThat(storedBinding.get("owner_binding_schema_version", Short.class)).isEqualTo((short) 1); + assertThat(storedBinding.get("version_id", Long.class)).isEqualTo(identity.localVersionKey()); + assertThat(storedBinding.get("canonical_version_id", UUID.class)) + .isEqualTo(identity.canonicalVersionId()); + assertThat(storedBinding.get("version_identity_operation_id", UUID.class)) + .isEqualTo(identity.operationId()); + assertThat(storedBinding.get("game_design_version_id", Long.class)) + .isEqualTo(GAME_DESIGN_VERSION_A); + assertThat(storedBinding.get("intake_request_digest", String.class)) + .isEqualTo(receipt.requestDigest()); AtomicBoolean retryRecapturedCheckpoint = new AtomicBoolean(); FrozenAttempt retry = @@ -119,7 +146,7 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { })); assertThat(retry).isEqualTo(frozen); assertThat(retryRecapturedCheckpoint).isFalse(); - assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); assertDatabaseTriggerRejects( () -> @@ -142,17 +169,64 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { + "SET current_publication_fence = NULL WHERE canonical_tenant_id = ? " + "AND version_id = ?", receipt.canonicalTenantId(), - 42L), + localVersionKey(identity(receipt, GAME_DESIGN_VERSION_A))), "World publication-fence owner binding or phase transition is immutable"); assertThat(repository.readAttempt(request)).contains(frozen); - assertThat(ownerCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); - assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); - assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); } @Test - void sameCanonicalTenantAndVersionRowCanBeLockedThroughDifferentIntakes() { + void schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "legacy-world"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "legacy-request", GAME_DESIGN_VERSION_A, 3L); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt (" + + "publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID(), + NAMESPACE, + receipt.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey(), + receipt.operationId(), + receipt.intakeRequestId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + "legacy-commit", + "e".repeat(64), + 2); + + assertThatThrownBy(() -> repository.readAttempt(request)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } + + @Test + void sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes() { UUID canonicalTenantId = UUID.randomUUID(); String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); WorldAuthoredSourceIntakeReceipt first = @@ -163,24 +237,68 @@ void sameCanonicalTenantAndVersionRowCanBeLockedThroughDifferentIntakes() { ownerTransaction() .execute( status -> { - repository.lockOpen(ownerBinding(first, 42)); + repository.lockOpen(ownerBinding(first, GAME_DESIGN_VERSION_A)); return null; }); ownerTransaction() .execute( status -> { - repository.lockOpen(ownerBinding(second, 42)); + repository.lockOpen(ownerBinding(second, GAME_DESIGN_VERSION_A)); return null; }); - assertThat(ownerCount(canonicalTenantId, 42)).isEqualTo(1L); - assertThat(ownerPhase(canonicalTenantId, 42)).isEqualTo("OPEN"); + assertThat(identity(first, GAME_DESIGN_VERSION_A).localVersionKey()) + .isNotEqualTo(identity(second, GAME_DESIGN_VERSION_A).localVersionKey()); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(2L); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("OPEN"); + } + + @Test + void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 8_101L); + WorldAuthoredVersionIdentityReceipt firstIdentity = identity(first, GAME_DESIGN_VERSION_A); + long secondGameDesignVersionId = firstIdentity.localVersionKey(); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_102L); + WorldAuthoredVersionIdentityReceipt secondIdentity = + identity(second, secondGameDesignVersionId); + assertThat(secondGameDesignVersionId).isEqualTo(firstIdentity.localVersionKey()); + assertThat(secondIdentity.localVersionKey()).isNotEqualTo(secondGameDesignVersionId); + + WorldDesignPublicationFenceEvidence firstRequest = + evidence(first, "shared-publication-request", GAME_DESIGN_VERSION_A, 5L); + WorldDesignPublicationFenceEvidence secondRequest = + evidence(second, "shared-publication-request", secondGameDesignVersionId, 5L); + FrozenAttempt firstFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(firstRequest, () -> SYNTHETIC_CHECKPOINT)); + FrozenAttempt secondFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(secondRequest, () -> SYNTHETIC_CHECKPOINT)); + + assertThat(secondFrozen.publicationFence()).isNotEqualTo(firstFrozen.publicationFence()); + long firstOwnerCount = ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondOwnerCount = ownerCount(canonicalTenantId, secondGameDesignVersionId); + long firstAttemptCount = attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondAttemptCount = attemptCount(canonicalTenantId, secondGameDesignVersionId); + assertThat(repository.readAttempt(firstRequest)).contains(firstFrozen); + assertThat(repository.readAttempt(secondRequest)).contains(secondFrozen); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstOwnerCount); + assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondOwnerCount); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstAttemptCount); + assertThat(attemptCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondAttemptCount); } @Test void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Exception { WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); - WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-concurrent", 42, 9L); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-concurrent", GAME_DESIGN_VERSION_A, 9L); CountDownLatch checkpointCaptured = new CountDownLatch(1); CountDownLatch releaseFirst = new CountDownLatch(1); CountDownLatch secondStarted = new CountDownLatch(1); @@ -223,7 +341,7 @@ void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Excepti FrozenAttempt secondResult = second.get(10, TimeUnit.SECONDS); assertThat(secondResult).isEqualTo(firstResult); assertThat(secondCapturedCheckpoint).isFalse(); - assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); } finally { releaseFirst.countDown(); executor.shutdownNow(); @@ -233,7 +351,8 @@ void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Excepti @Test void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws Exception { WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); - WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-writer-first", 42, 9L); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-writer-first", GAME_DESIGN_VERSION_A, 9L); CountDownLatch writerLocked = new CountDownLatch(1); CountDownLatch releaseWriter = new CountDownLatch(1); CountDownLatch freezeStarted = new CountDownLatch(1); @@ -275,7 +394,8 @@ void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws E FrozenAttempt frozen = freeze.get(10, TimeUnit.SECONDS); assertThat(checkpointCaptured).isTrue(); assertThat(frozen.checkpoint()).isEqualTo(SYNTHETIC_CHECKPOINT); - assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); } finally { releaseWriter.countDown(); executor.shutdownNow(); @@ -285,7 +405,8 @@ void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws E @Test void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exception { WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); - WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-freeze-first", 42, 9L); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-freeze-first", GAME_DESIGN_VERSION_A, 9L); CountDownLatch freezeLocked = new CountDownLatch(1); CountDownLatch releaseFreeze = new CountDownLatch(1); CountDownLatch writerStarted = new CountDownLatch(1); @@ -330,8 +451,9 @@ void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exceptio freeze.get(10, TimeUnit.SECONDS); assertThat(writer.get(10, TimeUnit.SECONDS)).isTrue(); - assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); - assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); } finally { releaseFreeze.countDown(); executor.shutdownNow(); @@ -346,20 +468,37 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_002L); WorldAuthoredSourceIntakeReceipt second = intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_002L); - WorldDesignPublicationFenceEvidence request = evidence(first, "request-7", 42, 9L); + WorldDesignPublicationFenceEvidence request = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 9L); FrozenAttempt frozen = ownerTransaction() .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); assertNoStateChange( canonicalTenantId, - 42, + GAME_DESIGN_VERSION_A, () -> ownerTransaction() .execute( status -> repository.claimFreeze( - evidence(second, "request-7", 42, 9L), () -> SYNTHETIC_CHECKPOINT))); + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + first.canonicalTenantId(), + identity(first, GAME_DESIGN_VERSION_A).canonicalVersionId(), + identity(first, GAME_DESIGN_VERSION_A).operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + second.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()), + () -> SYNTHETIC_CHECKPOINT))); UUID changedTenantId = UUID.randomUUID(); WorldDesignPublicationFenceEvidence changedAssociation = @@ -367,42 +506,111 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() changedTenantId, first, "request-7", - 42, + identity(first, GAME_DESIGN_VERSION_A), + GAME_DESIGN_VERSION_A, 9L, - PublicationDigestRequestBinding.full(changedTenantId.toString(), "42", "request-7")); + PublicationDigestRequestBinding.full( + changedTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_A), "request-7")); assertNoStateChange( canonicalTenantId, - 42, + GAME_DESIGN_VERSION_A, () -> ownerTransaction() .execute( status -> repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); - assertThat(ownerCount(changedTenantId, 42)).isZero(); + assertThat(ownerCount(changedTenantId, GAME_DESIGN_VERSION_A)).isZero(); + + WorldAuthoredVersionIdentityReceipt identity = identity(first, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence changedCanonicalVersion = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + UUID.randomUUID(), + identity.operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedCanonicalVersion, () -> SYNTHETIC_CHECKPOINT))); + + String changedSelectorWorkflow = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_B), "request-7") + .derivedWorkflowIdentity(); + WorldDesignPublicationFenceEvidence changedGameDesignSelector = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + identity.canonicalVersionId(), + identity.operationId(), + GAME_DESIGN_VERSION_B, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + changedSelectorWorkflow); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedGameDesignSelector, () -> SYNTHETIC_CHECKPOINT))); - WorldDesignPublicationFenceEvidence changedRequest = evidence(first, "request-8", 42, 9L); + WorldDesignPublicationFenceEvidence changedRequest = + evidence(first, "request-8", GAME_DESIGN_VERSION_A, 9L); assertNoStateChange( canonicalTenantId, - 42, + GAME_DESIGN_VERSION_A, () -> ownerTransaction() .execute( status -> repository.claimFreeze(changedRequest, () -> SYNTHETIC_CHECKPOINT))); - WorldDesignPublicationFenceEvidence changedEpoch = evidence(first, "request-7", 42, 10L); + WorldDesignPublicationFenceEvidence changedEpoch = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 10L); assertNoStateChange( canonicalTenantId, - 42, + GAME_DESIGN_VERSION_A, () -> ownerTransaction() .execute( status -> repository.claimFreeze(changedEpoch, () -> SYNTHETIC_CHECKPOINT))); WorldDesignPublicationFenceEvidence changedDigest = - evidence(first, "request-7", 42, 9L, "0".repeat(64), request.publishWorkflowId()); + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "0".repeat(64), + request.publishWorkflowId()); assertNoStateChange( canonicalTenantId, - 42, + GAME_DESIGN_VERSION_A, () -> ownerTransaction() .execute( @@ -412,33 +620,42 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() assertThat(repository.readAttempt(request)).contains(frozen); assertThatThrownBy( - () -> evidence(first, "request-7", 42, 9L, "F".repeat(64), request.publishWorkflowId())) + () -> + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "F".repeat(64), + request.publishWorkflowId())) .isInstanceOf(IllegalArgumentException.class); WorldAuthoredSourceIntakeReceipt missingCheckpointReceipt = intake(UUID.randomUUID(), "uncheckpointed-world"); WorldDesignPublicationFenceEvidence missingCheckpointRequest = - evidence(missingCheckpointReceipt, "request-missing-checkpoint", 43, 1L); + evidence(missingCheckpointReceipt, "request-missing-checkpoint", GAME_DESIGN_VERSION_B, 1L); assertThatThrownBy( () -> ownerTransaction() .execute( status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) .isInstanceOf(NullPointerException.class); - assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), 43)).isZero(); - assertThat(ownerPhase(canonicalTenantId, 42)).isEqualTo("FROZEN"); - assertThat(attemptCount(canonicalTenantId, 42)).isEqualTo(1L); + assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), GAME_DESIGN_VERSION_B)) + .isZero(); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); } - private void assertNoStateChange(UUID canonicalTenantId, long versionId, Runnable action) { - long ownersBefore = ownerCount(canonicalTenantId, versionId); - long attemptsBefore = attemptCount(canonicalTenantId, versionId); - String phaseBefore = ownerPhase(canonicalTenantId, versionId); + private void assertNoStateChange( + UUID canonicalTenantId, long gameDesignVersionId, Runnable action) { + long ownersBefore = ownerCount(canonicalTenantId, gameDesignVersionId); + long attemptsBefore = attemptCount(canonicalTenantId, gameDesignVersionId); + String phaseBefore = ownerPhase(canonicalTenantId, gameDesignVersionId); assertThatThrownBy(action::run) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); - assertThat(ownerCount(canonicalTenantId, versionId)).isEqualTo(ownersBefore); - assertThat(attemptCount(canonicalTenantId, versionId)).isEqualTo(attemptsBefore); - assertThat(ownerPhase(canonicalTenantId, versionId)).isEqualTo(phaseBefore); + assertThat(ownerCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(ownersBefore); + assertThat(attemptCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(attemptsBefore); + assertThat(ownerPhase(canonicalTenantId, gameDesignVersionId)).isEqualTo(phaseBefore); } private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) { @@ -498,44 +715,63 @@ private AuthoredWorldSourceEvidence source( private WorldDesignPublicationFenceEvidence evidence( WorldAuthoredSourceIntakeReceipt receipt, String publishRequestId, - long versionId, + long gameDesignVersionId, long versionStateEpoch) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); return evidence( receipt.canonicalTenantId(), receipt, publishRequestId, - versionId, + identity, + gameDesignVersionId, versionStateEpoch, PublicationDigestRequestBinding.full( - receipt.canonicalTenantId().toString(), Long.toString(versionId), publishRequestId)); + receipt.canonicalTenantId().toString(), + Long.toString(gameDesignVersionId), + publishRequestId)); } - private OwnerBinding ownerBinding(WorldAuthoredSourceIntakeReceipt receipt, long versionId) { + private OwnerBinding ownerBinding( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); return new OwnerBinding( NAMESPACE, receipt.canonicalTenantId(), - versionId, + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, receipt.intakeRequestId(), receipt.operationId(), + receipt.requestDigest(), receipt.sourceOperationId(), - receipt.sourceEvidenceDigest()); + receipt.sourceEvidenceDigest(), + receipt.receiptDigest()); + } + + private static long localVersionKey(WorldAuthoredVersionIdentityReceipt identity) { + return identity.localVersionKey(); } private WorldDesignPublicationFenceEvidence evidence( UUID tenantId, WorldAuthoredSourceIntakeReceipt receipt, String publishRequestId, - long versionId, + WorldAuthoredVersionIdentityReceipt identity, + long gameDesignVersionId, long versionStateEpoch, PublicationDigestRequestBinding binding) { return new WorldDesignPublicationFenceEvidence( NAMESPACE, tenantId, - versionId, + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, receipt.intakeRequestId(), receipt.operationId(), + receipt.requestDigest(), receipt.sourceOperationId(), receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), publishRequestId, FULL_REQUEST_DIGEST, versionStateEpoch, @@ -545,24 +781,64 @@ private WorldDesignPublicationFenceEvidence evidence( private WorldDesignPublicationFenceEvidence evidence( WorldAuthoredSourceIntakeReceipt receipt, String publishRequestId, - long versionId, + long gameDesignVersionId, long versionStateEpoch, String requestDigest, String workflowId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); return new WorldDesignPublicationFenceEvidence( NAMESPACE, receipt.canonicalTenantId(), - versionId, + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, receipt.intakeRequestId(), receipt.operationId(), + receipt.requestDigest(), receipt.sourceOperationId(), receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), publishRequestId, requestDigest, versionStateEpoch, workflowId); } + private WorldAuthoredVersionIdentityReceipt identity( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + UUID canonicalVersionId = stableId("canonical-version", receipt, gameDesignVersionId); + UUID readRequestId = stableId("version-state-read", receipt, gameDesignVersionId); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence stateEvidence = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + receipt.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return ownerTransaction() + .execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(receipt, stateEvidence)); + } + + private static UUID stableId( + String domain, WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + return UUID.nameUUIDFromBytes( + (domain + ":" + receipt.operationId() + ":" + Long.toString(gameDesignVersionId)) + .getBytes(StandardCharsets.UTF_8)); + } + private TransactionTemplate ownerTransaction() { TransactionTemplate transaction = new TransactionTemplate(transactionManager); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -571,37 +847,57 @@ private TransactionTemplate ownerTransaction() { return transaction; } - private long ownerCount(UUID tenantId, long versionId) { + private long ownerCount(UUID tenantId, long gameDesignVersionId) { return count( - "SELECT COUNT(*) FROM world_design_publication_fence_owner " - + "WHERE canonical_tenant_id = ? AND version_id = ?", + "SELECT COUNT(*) FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", tenantId, - versionId); + gameDesignVersionId); } - private long attemptCount(UUID tenantId, long versionId) { + private long attemptCount(UUID tenantId, long gameDesignVersionId) { return count( - "SELECT COUNT(*) FROM world_design_publication_fence_attempt " - + "WHERE canonical_tenant_id = ? AND version_id = ?", + "SELECT COUNT(*) FROM world_design_publication_fence_attempt fence_attempt " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_attempt.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_attempt.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_attempt.version_id " + + "WHERE fence_attempt.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", tenantId, - versionId); + gameDesignVersionId); } - private String ownerPhase(UUID tenantId, long versionId) { + private String ownerPhase(UUID tenantId, long gameDesignVersionId) { var row = dsl.fetchOne( - "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " - + "WHERE canonical_tenant_id = ? AND version_id = ?", + "SELECT CASE WHEN COUNT(*) = 0 THEN NULL " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'OPEN') THEN 'OPEN' " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'FROZEN') THEN 'FROZEN' " + + "ELSE 'MIXED' END " + + "FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", tenantId, - versionId); + gameDesignVersionId); if (row == null) { throw new IllegalStateException("World publication-fence owner phase query returned no row"); } return row.get(0, String.class); } - private long count(String sql, UUID tenantId, long versionId) { - return Objects.requireNonNull(dsl.fetchOne(sql, tenantId, versionId)).get(0, Long.class); + private long count(String sql, UUID tenantId, long gameDesignVersionId) { + return Objects.requireNonNull(dsl.fetchOne(sql, tenantId, gameDesignVersionId)) + .get(0, Long.class); } private void awaitOwnerRowLockWait() { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java new file mode 100644 index 0000000000..4fe77572b9 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import org.junit.jupiter.api.Test; + +class WorldAuthoredGraphSnapshotTest { + private static final String DIGEST = "a".repeat(64); + + @Test + void captureRequestPreservesTypedEpochAndCanonicalizesTupleOrder() { + OwnedAffectedTuple scope = + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", + "ROOM", + "9223372036854775806", + "ZONE_SUBTREE", + "9223372036854775805", + "9223372036854775807"); + OwnedAffectedTuple aggregate = + new OwnedAffectedTuple("WORLD_MANAGEMENT", "REGION", "4", "", "", "9"); + + CaptureRequest request = + new CaptureRequest( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + List.of(scope, aggregate)); + + assertThat(request.suppliedOwnedAffectedTuples()).containsExactly(aggregate, scope); + assertThat(scope.expectedEpoch()).isEqualTo("9223372036854775807"); + } + + @Test + void changedOrAmbiguousTupleDeclarationsAreRejected() { + assertThatThrownBy( + () -> new OwnedAffectedTuple("GAME_DESIGN", "ROOM", "1", "ZONE_SUBTREE", "2", "3")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "2", "03")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "", "3")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sourceAndReceiptDigestsRetainTheirRequiredPrefix() { + assertThatThrownBy( + () -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + DIGEST, + "sha256:" + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidenceDigest"); + + assertThatThrownBy( + () -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + "sha256:" + DIGEST, + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intakeReceiptDigest"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java index 9aa83e08df..57874f0549 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java @@ -15,32 +15,46 @@ class WorldDesignPublicationFenceEvidenceTest { UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final UUID SOURCE_OPERATION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION_IDENTITY_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String INTAKE_REQUEST_DIGEST = "sha256:" + "1".repeat(64); private static final String SOURCE_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String INTAKE_RECEIPT_DIGEST = "sha256:" + "2".repeat(64); private static final String FULL_REQUEST_DIGEST = "f".repeat(64); private static final String CONTENT_DIGEST = "b".repeat(64); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; @Test void bindsFullVersionToTheCanonicalPublicationDigestRequestGrammar() { PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7"); + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); WorldDesignPublicationFenceEvidence evidence = evidence("request-7", FULL_REQUEST_DIGEST, binding.derivedWorkflowIdentity()); assertThat(evidence.publicationBinding()).usingRecursiveComparison().isEqualTo(binding); assertThat(evidence.publicationBinding().scopeKindValue()).isEqualTo("FULL_VERSION"); - assertThat(evidence.publicationBinding().versionId()).isEqualTo("42"); + assertThat(evidence.publicationBinding().versionId()) + .isEqualTo(Long.toString(GAME_DESIGN_VERSION_ID)); assertThat(evidence.publicationBinding().baseVersionId()).isEmpty(); assertThat(evidence.publicationBinding().scriptPatchVersion()).isEmpty(); assertThat(evidence.requestDigest()).isEqualTo(FULL_REQUEST_DIGEST); assertThat(evidence.requestDigest()).isNotEqualTo(binding.requestDigest()); assertThat(evidence.publishWorkflowId()) .isEqualTo("publish:" + TENANT_ID + ":publish-request:request-7"); + assertThat(evidence.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); + assertThat(evidence.versionIdentityOperationId()).isEqualTo(VERSION_IDENTITY_OPERATION_ID); + assertThat(evidence.ownerBinding().intakeRequestDigest()).isEqualTo(INTAKE_REQUEST_DIGEST); } @Test void rejectsChangedOrOmittedRequestAndWorkflowBindings() { PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7"); + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); assertThatIllegalArgumentException() .isThrownBy(() -> evidence("request-7", binding.requestDigest(), "publish:wrong")); @@ -64,11 +78,34 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { new WorldDesignPublicationFenceEvidence( "FireMUD", TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, 42, INTAKE_REQUEST_ID, INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, SOURCE_OPERATION_ID, SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST.substring("sha256:".length()), "request-7", validDigest(), 9, @@ -79,11 +116,15 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { new WorldDesignPublicationFenceEvidence( "firemud", new UUID(0L, 0L), + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, 42, INTAKE_REQUEST_ID, INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, SOURCE_OPERATION_ID, SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, "request-7", validDigest(), 9, @@ -94,11 +135,34 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { new WorldDesignPublicationFenceEvidence( "firemud", TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, 42, INTAKE_REQUEST_ID, INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, SOURCE_OPERATION_ID, "a".repeat(64), + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST.substring("sha256:".length()), + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, "request-7", validDigest(), 9, @@ -133,7 +197,7 @@ void checkpointRequiresACompleteCanonicalDigestTuple() { private static WorldDesignPublicationFenceEvidence evidence( String requestId, String digest, String workflowId) { - return evidence(requestId, digest, workflowId, 42, 9L); + return evidence(requestId, digest, workflowId, GAME_DESIGN_VERSION_ID, 9L); } private static WorldDesignPublicationFenceEvidence evidence( @@ -141,11 +205,15 @@ private static WorldDesignPublicationFenceEvidence evidence( return new WorldDesignPublicationFenceEvidence( "firemud", TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, versionId, INTAKE_REQUEST_ID, INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, SOURCE_OPERATION_ID, SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, requestId, digest, epoch, @@ -157,7 +225,8 @@ private static String validDigest() { } private static String validWorkflow() { - return PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7") + return PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7") .derivedWorkflowIdentity(); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java new file mode 100644 index 0000000000..a68f3e5b90 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java @@ -0,0 +1,540 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan.RegionRevision; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionCommitPlanTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String PREFIXED_DIGEST = "sha256:" + "a".repeat(64); + private static final String OTHER_OWNER_PAYLOAD = "not decoded by the World plan"; + + @Test + void acceptsOrderedMultiRegionSubsetAndPreservesMixedOwnerBinding() { + UUID firstRevision = uuid(5); + UUID secondRevision = uuid(6); + DraftCommitBinding binding = + binding( + List.of( + otherRevision("0"), + worldRevision("1", firstRevision, regionJson(firstRevision, COMMIT_ID, "7", 2, 4)), + worldRevision( + "2", secondRevision, regionJson(secondRevision, COMMIT_ID, "19", 8, 3))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4), + worldUnit("19", "AGGREGATE", "19", 8), + worldUnit("19", "REGION_SUBTREE", "19", 3), + otherUnit())); + + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding = ownerBinding(); + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding); + + assertThat(plan.binding()).isSameAs(binding); + assertThat(plan.ownerBinding()).isSameAs(ownerBinding); + assertThat(plan.binding().requestId()).isEqualTo(REQUEST_ID); + assertThat(plan.binding().baseCommitId()).isEqualTo("base-commit-17"); + assertThat(plan.regionRevisions()) + .extracting(RegionRevision::revisionOrder) + .containsExactly("1", "2"); + assertThat(plan.regionRevisions()) + .extracting(revision -> revision.mutation().getAggregateId()) + .containsExactly("7", "19"); + assertThat(plan.regionRevisions().get(0).mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(2); + assertThat(plan.regionRevisions().get(0).mutation().getExpectedDraftScopeRevisionEpoch()) + .isEqualTo(4); + assertThat(plan.regionRevisions().get(1).mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(8); + assertThat(plan.regionRevisions().get(1).mutation().getExpectedDraftScopeRevisionEpoch()) + .isEqualTo(3); + } + + @Test + void rejectsMissingContainingScopeAndAdditionalOrMismatchedWorldTuples() { + UUID revisionId = uuid(5); + String payload = regionJson(revisionId, COMMIT_ID, "7", 2, 4); + List revisions = + List.of(worldRevision("0", revisionId, payload)); + + assertPlanRejected(binding(revisions, List.of(worldUnit("7", "AGGREGATE", "7", 2)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4), + worldUnit("7", "ZONE_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 3), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 5)))); + } + + @Test + void rejectsChangedTargetAndProtoCommitOrRevisionIdentity() { + UUID revisionId = uuid(5); + List revisions = + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))); + List units = + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)); + DraftCommitBinding valid = binding(revisions, units); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + WorldDraftRegionCommitPlan.create( + valid, + ownerBinding( + TENANT_ID, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + GAME_DESIGN_VERSION_ID))); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(revisionId, uuid(9), "7", 2, 4))), + units)); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(uuid(10), COMMIT_ID, "7", 2, 4))), + units)); + } + + @Test + void comparesOnlyTheSharedCanonicalTargetAndGameDesignVersionSelector() { + UUID revisionId = uuid(5); + List revisions = + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))); + List units = + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)); + + DraftCommitBinding differentTenant = + binding(targetProof(uuid(50), VERSION_ID, GAME_DESIGN_VERSION_ID), revisions, units); + DraftCommitBinding differentGameDesignVersion = + binding(targetProof(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID + 1L), revisions, units); + + assertPlanRejected(differentTenant, ownerBinding()); + assertPlanRejected(differentGameDesignVersion, ownerBinding()); + assertPlanRejected( + binding(revisions, units), + ownerBinding(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID + 1L)); + } + + @Test + void rejectsUnknownPayloadFieldsAndMalformedTypedJson() { + UUID revisionId = uuid(5); + String valid = regionJson(revisionId, COMMIT_ID, "7", 2, 4); + String withUnknownField = valid.substring(0, valid.length() - 1) + ",\"unrecognized\":true}"; + + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, withUnknownField)), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, "{")), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + + @Test + void rejectsNoncanonicalOrOutOfRangeRegionIdsAndMismatchedScopeIds() { + UUID revisionId = uuid(5); + for (String id : List.of("0", "01", "+7", " 7", "9223372036854775808")) { + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, id, 2, 4))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + assertPlanRejected( + binding( + List.of( + worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4, "8"))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + + @Test + void rejectsNegativeMaxAndBindingMismatchedEpochs() { + UUID revisionId = uuid(5); + assertPlanRejected( + planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", -1, 4), 0, 4)); + assertPlanRejected( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", Long.MAX_VALUE, 4), + Long.MAX_VALUE, + 4)); + assertPlanRejected( + planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, -1), 2, 0)); + assertPlanRejected( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", 2, Long.MAX_VALUE), + 2, + Long.MAX_VALUE)); + assertPlanRejected(planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4), 3, 4)); + + WorldDraftRegionCommitPlan plan = + WorldDraftRegionCommitPlan.create( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", Long.MAX_VALUE - 1, 4), + Long.MAX_VALUE - 1, + 4), + ownerBinding()); + assertThat(plan.regionRevisions().getFirst().mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(Long.MAX_VALUE - 1); + } + + @Test + void rejectsDuplicateRegionMutationsAndUnsupportedCreateDeleteReplacementOrGenerationShapes() { + UUID firstRevision = uuid(5); + UUID secondRevision = uuid(6); + assertPlanRejected( + binding( + List.of( + worldRevision("0", firstRevision, regionJson(firstRevision, COMMIT_ID, "7", 2, 4)), + worldRevision( + "1", secondRevision, regionJson(secondRevision, COMMIT_ID, "7", 2, 4))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + planBinding(firstRevision, regionJson(firstRevision, COMMIT_ID, "", 2, 4), 2, 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UNSPECIFIED) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setScopeMutationPolicy( + WorldDesignScopeMutationPolicy + .WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(firstRevision.toString()) + .setCommitId(COMMIT_ID.toString()) + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType( + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE) + .setAggregateId("7") + .setExpectedDraftRevisionEpoch(2) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("7") + .setExpectedDraftScopeRevisionEpoch(4) + .setWorldGenerationSubtree( + WorldGenerationSubtreeDesignMutation.getDefaultInstance()) + .build()), + 2, + 4)); + } + + @Test + void rejectsBlankNameNonfiniteOrNegativeSpacingAndNonRegionPayload() { + UUID revisionId = uuid(5); + for (double spacing : List.of(Double.NaN, Double.POSITIVE_INFINITY, -0.5d)) { + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion( + RegionDesignMutation.newBuilder() + .setName("North") + .setSpacingMultiplier(spacing)) + .build()), + 2, + 4)); + } + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion( + RegionDesignMutation.newBuilder().setName(" ").setSpacingMultiplier(1.0d)) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder().clearRegion().build()), + 2, + 4)); + } + + @Test + void preservesZeroSpacingForTheExistingWorldDefaultRule() { + UUID revisionId = uuid(5); + String payload = + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion(RegionDesignMutation.newBuilder().setName("Northern Reach")) + .build()); + DraftCommitBinding binding = + binding( + List.of(worldRevision("0", revisionId, payload)), + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4))); + + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + + assertThat(plan.regionRevisions().getFirst().mutation().getRegion().getSpacingMultiplier()) + .isZero(); + assertThat(plan.binding().revisions().getFirst().payload()).isEqualTo(payload); + } + + @Test + void sharedBindingRejectsDuplicateAffectedWorldTuples() { + UUID revisionId = uuid(5); + List units = + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4)); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + binding( + List.of( + worldRevision( + "0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))), + units)); + } + + @Test + void planCollectionsAreDefensiveAndKeepTheExactSharedBaseAndRequest() { + UUID revisionId = uuid(5); + ArrayList supplied = + new ArrayList<>( + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4)))); + DraftCommitBinding binding = + binding( + supplied, + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4))); + supplied.clear(); + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + + assertThat(plan.binding().requestId()).isEqualTo(REQUEST_ID); + assertThat(plan.binding().baseCommitId()).isEqualTo("base-commit-17"); + assertThat(plan.regionRevisions()).hasSize(1); + assertThatThrownBy(() -> plan.regionRevisions().add(plan.regionRevisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static DraftCommitBinding planBinding( + UUID revisionId, String payload, long aggregateEpoch, long scopeEpoch) { + return binding( + List.of(worldRevision("0", revisionId, payload)), + List.of( + worldUnit("7", "AGGREGATE", "7", aggregateEpoch), + worldUnit("7", "REGION_SUBTREE", "7", scopeEpoch))); + } + + private static DraftCommitBinding binding( + List revisions, List units) { + return binding(targetProof(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID), revisions, units); + } + + private static DraftCommitBinding binding( + DraftCommitBinding.TargetProof target, + List revisions, + List units) { + return DraftCommitBinding.create( + target, REQUEST_ID, COMMIT_ID, "base-commit-17", revisions, units); + } + + private static DraftCommitBinding.TargetProof targetProof( + UUID tenantId, UUID versionId, long gameDesignVersionRowId) { + return new DraftCommitBinding.TargetProof( + tenantId, + versionId, + gameDesignVersionRowId, + "tenant-123", + 1001L, + "tenant-123", + "NEW_GAME_ROW"); + } + + private static DraftCommitBinding.RevisionPayload worldRevision( + String order, UUID revisionId, String payload) { + return new DraftCommitBinding.RevisionPayload( + order, revisionId, Owner.WORLD_MANAGEMENT, payload); + } + + private static DraftCommitBinding.RevisionPayload otherRevision(String order) { + return new DraftCommitBinding.RevisionPayload( + order, uuid(30), Owner.GAME_LOGIC, OTHER_OWNER_PAYLOAD); + } + + private static AffectedUnit worldUnit( + String aggregateId, String scopeType, String scopeId, long expectedEpoch) { + return new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregateId, + scopeType, + scopeId, + Long.toString(expectedEpoch)); + } + + private static AffectedUnit otherUnit() { + return new AffectedUnit( + Owner.GAME_LOGIC, "ABILITY", "ability-77", "AGGREGATE", "ability-77", "0"); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return ownerBinding(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding( + UUID tenantId, UUID versionId, long gameDesignVersionId) { + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + "firemud", + tenantId, + versionId, + uuid(40), + gameDesignVersionId, + uuid(41), + uuid(42), + PREFIXED_DIGEST, + uuid(43), + PREFIXED_DIGEST, + PREFIXED_DIGEST); + } + + private static String regionJson( + UUID revisionId, UUID commitId, String regionId, long aggregateEpoch, long scopeEpoch) { + return regionJson(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, regionId); + } + + private static String regionJson( + UUID revisionId, + UUID commitId, + String regionId, + long aggregateEpoch, + long scopeEpoch, + String scopeId) { + return json( + regionRevision(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, scopeId)); + } + + private static WorldDesignMutationRevision regionRevision( + UUID revisionId, UUID commitId, String regionId, long aggregateEpoch, long scopeEpoch) { + return regionRevision(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, regionId); + } + + private static WorldDesignMutationRevision regionRevision( + UUID revisionId, + UUID commitId, + String regionId, + long aggregateEpoch, + long scopeEpoch, + String scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(regionId) + .setExpectedDraftRevisionEpoch(aggregateEpoch) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scopeId) + .setExpectedDraftScopeRevisionEpoch(scopeEpoch) + .setRegion( + RegionDesignMutation.newBuilder().setName("Northern Reach").setSpacingMultiplier(1.25d)) + .build(); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "Test mutation could not be rendered as protobuf JSON", exception); + } + } + + private static void assertPlanRejected(DraftCommitBinding binding) { + assertPlanRejected(binding, ownerBinding()); + } + + private static void assertPlanRejected( + DraftCommitBinding binding, WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldDraftRegionCommitPlan.create(binding, ownerBinding)); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", value, value)); + } +} From 8568f5c697a43eb98a251b4df8ab9f464ad38433 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:53:58 +1300 Subject: [PATCH 02/11] Bind publication workflow to the exact existing authored Draft --- .github/workflows/ci.yml | 4 + .../game-design-service/api-contracts.md | 12 +- .../game-design-service/version-control.md | 2 +- design/project-management/ai-observations.md | 5 + ...ame-authoring-publishing-and-activation.md | 4 +- .../player-access-and-session.md | 2 +- .../world-runtime-and-movement.md | 2 +- .../game-design/v1/game_design_service.proto | 5 + ...thoredDraftPublishSelectionRepository.java | 25 +- .../DraftCommitCoordinatorRepository.java | 6 +- .../gamedesign/service/VersionService.java | 4 +- .../service/impl/GameDesignGrpcService.java | 24 +- .../impl/PublishAttemptServiceImpl.java | 3 +- .../service/impl/PublishWorkflowRequest.java | 21 +- .../TemporalVersionPublishOrchestrator.java | 10 +- .../VersionPublishCommandServiceImpl.java | 260 +++++--- .../service/impl/VersionServiceImpl.java | 16 +- ...uthored_draft_publish_request_identity.sql | 5 + ...ishSelectionRepositoryIntegrationTest.java | 315 ++++++++- ...emptServiceTransactionIntegrationTest.java | 262 ++++++-- .../impl/GameDesignGrpcServiceTest.java | 263 +++++--- ...ectedAuthoredDraftPublishWorkflowTest.java | 168 +++++ ...poralVersionPublishActivitiesImplTest.java | 20 +- ...emporalVersionPublishOrchestratorTest.java | 11 +- .../VersionPublishCommandServiceImplTest.java | 607 +++++++++++------- .../service/impl/VersionServiceImplTest.java | 74 +-- .../tenant/WorldAuthoredGraph.java | 145 +++++ .../WorldAuthoredGraphSnapshotCapture.java | 29 +- .../tenant/WorldDraftRegionGraphStager.java | 153 +++++ ...DesignPublicationFenceIntegrationTest.java | 5 +- .../tenant/WorldAuthoredGraphTest.java | 140 ++++ .../WorldDraftRegionGraphStagerTest.java | 366 +++++++++++ 32 files changed, 2399 insertions(+), 569 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f634ae11e..c236db859f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2148,6 +2148,10 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#reusesExistingAuthoredVersionAndExactReplayIgnoresLaterServerState()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#rejectsPublishedScriptOnlyUnmappedPartialStaleAndMismatchedTargets()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#failedReservationTransactionLeavesNoSelection()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#samePublicationRequestCannotSelectAnotherVersionInTheSameTenant()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#concurrentPublicationRequestClaimsAcrossVersionsRetainOnlyOneSelection()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#v44PreservesExactSelectionsRetainedAtV43()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#v44RejectsConflictingRetainedRequestAcrossVersionsWithoutDiscardingEitherHistory()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#versionRowLockSerializesSelectionAgainstApplicationSlotClaim()' \ game-design-service diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a2681c5f6c..b92a694ac6 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -143,6 +143,8 @@ The eventual creator-facing proto/OpenAPI shape must expose these semantics with Concrete RPC names, message fields, enums, pagination, and transport exposure remain deferred until the proto/OpenAPI contract is implemented. Whatever shape is selected must preserve the authority and visibility rules in ADR 0129. +Full-version publication selects an existing authored Draft through `PublishVersionRequest`: canonical `tenant_id` and `version_id`, stable `publish_request_id`, positive canonical decimal `expected_version_state_epoch`, `notes`, and the exact `selected_commit_request_id`, `selected_commit_id` and `selected_commit_digest`. The first durable selection binds all of those fields to the synchronized commit and its complete owner evidence. A tenant/request identity cannot select a second Version. Changed or omitted selection input conflicts before a new attempt or attachment to a workflow; an exact retry retains the original selection instead of substituting the current Draft. Game Design resolves private storage keys from its persisted canonical association. Private tenant or Version keys do not replace the canonical target or publication-workflow identity. + The [Account-owned exact-operation authorization fence](../account-service/api-contracts.md#account-owned-authored-draft-authorization-fence) covers both World's owner commit and Game Design's final authoritative commit. Game Design preserves the original operation and complete binding during automatic recovery and supplies immutable, authenticated final commit or no-commit readback. It must not treat an Account capture or finalization result as permission for a later commit, or expose a partial World outcome as a synchronized Draft. Source changes remain subject to the Account-owned ordering until both participant outcomes are definitive; this producer/consumer integration is not established by the coordinator storage alone. For every creator-intent `SaveRevision`, including revision-only requests, the exact Account party, acceptance-evidence, and material-acceptance-generation authorization must remain valid through Game Design's authoritative commit boundary. A preflight Account read alone is insufficient. If the authority is stale, mismatched, unavailable, or uncertain at that boundary, Game Design aborts the local transaction; no creator mutation or staged artifact becomes authoritative or externally reachable, and any staged artifact is cleanup/quarantine state, not success. The implementation must use commit-bound Account authorization/fence or equivalent validation without this contract selecting its mechanism. @@ -151,9 +153,9 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status -The current full-version reservation creates a new empty `Version` rather than selecting the existing authored Draft and its synchronized commit. Its public request does not carry that Draft/commit binding, and the World freeze and complete released-graph readback are not wired into this path. Consequently, existing revision rows, digest-read authentication, and release-bundle metadata do not prove that publication contains the edited world. The required durable commit and synchronized-visibility contract remains [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md); progress and remaining participant and Account authorization gates belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The full-version request now carries the exact existing authored-Draft selection. Internal reservation retains that selection and uses its server-resolved existing Version rather than allocating a new empty Version; storage additionally enforces one Version per canonical tenant/request identity. Public full-version publication remains denied with `PUBLICATION_AUTHORIZATION_UNAVAILABLE` before workflow dispatch or mutation because the current Account actor/role/party/terms producer and authenticated owner freeze/materialization are missing. Internal pending execution also denies at the unresolved canonical owner-carrier boundary before participant dispatch or content export. Existing revision rows, digest-read authentication, release-bundle metadata and selection storage therefore do not prove publication of the edited world. The required durable commit and synchronized-visibility contract remains [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md); progress and remaining participant and Account authorization gates belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication-read APIs, and first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are present in the current proto/service path. Public full-version `PublishVersion` requires the Temporal `publish` orchestrator and returns `PUBLISH_WORKFLOW_UNAVAILABLE` when it is absent or disabled. The underlying command and readback callbacks remain workflow activities; they are not a synchronous public fallback. The four owner-to-owner digest reads use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding. End-to-end Temporal publication remains unproved: Automation rejects both unsupported digest scopes, Game Logic fails closed without the owner-local rule-input manifest/provenance, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). An exception after external export or release-bundle write leaves the original attempt outcome pending until reconciliation reads back its identity and all release evidence; a failure marker alone does not prove terminality or safe cleanup. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication-read APIs, and first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are present in the current proto/service path. Full-version publication requires the durable Temporal `publish` workflow once its authorization and owner prerequisites are implemented; the present public operation denies earlier on missing authorization. The underlying command and readback callbacks are not a synchronous public fallback. The four owner-to-owner digest reads use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding, but their current legacy numeric/private content carriers do not establish the selected canonical Draft boundary. End-to-end Temporal publication remains unproved: Automation rejects both unsupported digest scopes, Game Logic fails closed without the owner-local rule-input manifest/provenance, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). An exception after external export or release-bundle write leaves the original attempt outcome pending until reconciliation reads back its identity and all release evidence; a failure marker alone does not prove terminality or safe cleanup. `UploadPluginBundle` parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` row. Current intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; the current proto/storage also lack an append-only signature-evidence ledger and append RPC. `PublishPluginVersion` validates the uploaded bundle and published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and best-effort supersedes older published versions. The candidate now compares the dedicated `GAME_LOGIC` participant `abilitySchemaDigest` retained with its exact full-version release scope, commit and supported digest schema; an aggregate digest, absent value or wrong owner is rejected without publication mutation. The normal Game Logic ability-schema source producer and complete activation compatibility remain unproved. `RevokePluginVersion` and `ListPluginVersionStatusEvents` provide the current design-time revoke and append-only publication-event read surfaces; dedicated ability-schema proof and broader activation-time alias/binding validation remain open. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. @@ -184,14 +186,14 @@ For retries, World Management's ledger lookup makes the same mutation identity ( The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. -When Temporal is disabled or its orchestrator bean is absent, public `PublishVersion` returns `PUBLISH_WORKFLOW_UNAVAILABLE` before invoking the publish command. The underlying command and reconciliation callbacks remain for actual workflow execution, not as a synchronous public fallback. The Temporal authorization and worker/readback proofs, exact participant content, and restart-independent terminal workflow status remain unproved. Any outcome after external export or a release-bundle write requires readback of the original attempt identity and all release evidence rather than inferring safe cleanup. +Public `PublishVersion` currently denies on missing complete Account authorization before invoking the Temporal orchestrator or publish command, even when a workflow bean is present. The underlying command and reconciliation callbacks are not a synchronous public fallback. The Temporal authorization and worker/readback proofs, exact participant content, and restart-independent terminal workflow status remain unproved. Any retained outcome after external export or a release-bundle write requires readback of the original attempt identity and all release evidence rather than inferring safe cleanup. The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). ## gRPC APIs - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `PublishVersion` – target publication freezes the exact existing authored Draft and synchronized commit. The current Temporal path instead reserves a new empty Version, as recorded above. Exact workload authorization for participant digest reads is implemented; this is not Account creator/terms authorization through the owner commit, nor complete content publication proof. +- `PublishVersion` – carries the exact existing authored-Draft selection, but currently denies before public workflow dispatch because complete Account authorization and authenticated owner freeze/materialization are unavailable. Internal selection and attempt storage do not allocate an empty replacement Version. Exact workload authorization for participant digest reads is not Account creator/terms authorization through the owner commit or complete content publication proof. - `PublishScriptPatchVersion` – requests script-only publication for a base-version/patch identity. The current composed path fails at the Automation participant digest gate before notification; see Implementation Status and [Version Control](version-control.md#script-patch-versions-and-runtime-behavior) for the exact failure and the conditional later client-preflight seam. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. @@ -242,7 +244,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – target publication of the exact frozen authored Draft; the current request/reservation does not yet select that Draft or synchronized commit. Callers must provide a stable `publish_request_id`. The service derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. If the Temporal orchestrator is absent or disabled, the public operation fails closed with `PUBLISH_WORKFLOW_UNAVAILABLE`; the local publish command is used as a workflow activity, not as a synchronous fallback. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed; Account commit-bound creator/terms authorization, complete authored content, and live mounted-certificate/activity proof remain distinct outstanding gates. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – carries the exact existing-Draft selection described in [Draft commit semantics](#draft-commit-and-proposal-semantics-target-state). The current public operation fails closed with `PUBLICATION_AUTHORIZATION_UNAVAILABLE` before dispatch or mutation. The target uses one canonical tenant/request workflow identity and succeeds only after terminal workflow success and complete release commit/readback; internal selection or a local command is not a synchronous authorization fallback. A retained post-export or post-bundle exception requires readback of the original attempt, bundle, Version, artifact and object-store evidence rather than inferring terminal failure or issuing a new publish. Account commit-bound authorization, canonical participant content, owner freeze and live activity proof remain outstanding gates. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 5bfa04fc8b..81c4233db9 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -205,7 +205,7 @@ Rules: - `digest-gate participant`: supplies digest attestation used to block/allow publish but does not necessarily execute a workflow step. For full publishes, Game Logic is digest-gate only unless/until it owns explicit publish-time finalize steps. - A service outside the matrix for the current publish type may be validated separately, but must not block digest gating for that publish type. -- `PublishVersionRequest` must carry a stable `publish_request_id`; the Game Design Temporal `publish` workflow uses that caller-visible request identity as its durable business key, so retries must reuse the same request id instead of minting a fresh client UUID on each attempt. +- `PublishVersionRequest` binds the exact existing-Draft selection defined by the [Game Design API contract](./api-contracts.md#draft-commit-and-proposal-semantics-target-state). The Temporal `publish` workflow derives its business identity from the canonical tenant and stable caller-visible `publish_request_id`; retries preserve the original selection rather than minting a new request or substituting a later synchronized commit. Private storage selectors remain local implementation details. - Orchestrator routing is strict by publish type/scope: - Full publish requests (`scope.versionId`) call only participants in the full-publish matrix. - Script-only publish requests (`scope.scriptPatchVersion`) call only script-patch participants. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6c0c2b671a..724790ce40 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -426,3 +426,8 @@ Entry format: - Context: the new Game Design-to-World composition fixture added a World service test dependency. Its service JAR also supplied `db/migration`, so existing Game Design classpath-based Flyway fixtures failed on duplicate V1 migrations in CI; Docker-free local checks had skipped that setup. All eight new database cases passed, but six other required cases did not execute. - Outcome: selecting the World dependency's standard classes-only variant preserves its implementation and transitive dependencies without its migration resources. A resolved runtime-classpath diagnostic and full affected checks pass; exact corrected-state PostgreSQL execution is still required. - Expected pattern: for cross-service test composition, inspect resolved runtime artifacts as well as compilation. Keep owner migrations explicitly isolated and verify existing owner suites still execute; do not modify migrations or weaken fixtures to accommodate resource leakage. + +- `2026-10-06`: Revalidate helper execution state after an IDE restart + - Context: two preserved #3004 helper contexts appeared running after restart and accepted continuation messages, but interrupt readback returned `pending_init` for one and `not_found` for the other. No new scoped edits or handoff supported treating either continuation as productive execution. + - Outcome: Document preserved the dirty implementation, explicitly resumed the fixture context, and recorded the missing migration continuation as failed before retrying its same bounded assignment in a fresh context. No provider review was restarted; model capacity was not established as the cause. + - Expected pattern: distinguish sidebar/list state and accepted dispatch from demonstrated execution. Recover only the affected bounded contexts, preserve their edits and findings, and record unavailable attempts without claiming review or validation credit. The restart-state discrepancy remains unexplained. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index ad76cf5aea..cfe6cd069a 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The authored-publication candidate adds an internal durable Draft coordinator and existing-Draft publication selection. One shared complete-input codec retains the canonical target, exact base, ordered full revisions and complete declared owner/aggregate/scope epochs; immutable per-owner results and the synchronized visibility record retain exact binding and result bytes. V42 stores coordination, an application slot and immutable definitive final-abort evidence; a complete terminal mixed vector becomes failed nonpublication without advancing the prior synchronized view or rewriting owner outcomes. V43 reserves the caller-selected synchronized commit of an existing full Draft Version instead of allocating an empty publication Version. These are unwired storage components, not authenticated owner producers, normal editor visibility, a complete publication workflow or release proof. The current public full-version publish implementation still creates a new empty Version and does not consume this selection. The consolidated Core/Account/Game Design/World checks, schema generation, three boot JARs, formatting, analyzers, links and Markdown pass with 1,931 clean recorded unit executions and one MinIO skip; the final 12-second gate executes 12 tasks and reuses 142. All 545 PostgreSQL nodes, including nine coordinator and four selection methods, compile and skip locally without Docker. CI retains raw XML and strictly requires the named methods without skips; their runner execution remains open. Account commit-time authorization, typed owner completeness, partial-application recovery, participant evidence and release/terminal handoff remain required before the new normal path is enabled. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) owns that contract. +The authored-publication candidate adds an internal durable Draft coordinator and exact existing-Draft selection. The shared complete-input codec retains the canonical target, exact base, ordered full revisions and complete declared owner/aggregate/scope epochs. V42 retains immutable owner results, definitive final abort and synchronized visibility; a definitive mixed vector becomes failed nonpublication without rewriting outcomes or advancing the prior view. V43 retains the first selected synchronized commit; V44 additionally enforces one Version per canonical tenant/publication-request identity without discarding conflicting retained history. The request, Temporal envelope and attempt carry the complete original selection and use the server-resolved existing Version, not a newly allocated empty Version. Public publication denies before dispatch or mutation while the current Account actor/role/party/terms producer and authenticated owner freeze/materialization are missing. Internal selected pending execution also denies before incompatible legacy participant calls or export. Historical provable terminal readback remains separate and does not manufacture missing selection evidence. These components do not prove normal synchronized editor reads, authenticated owner commits or complete release publication. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) owns that contract. + +The earlier consolidated four-module gate passed with 1,931 clean unit results and one MinIO skip, while all 545 PostgreSQL nodes skipped locally without Docker. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for `c5fd96e935028b72182d58a611152bee6a8e533b`, records nine coordinator methods executing with four passes and five failures; all four selection methods failed. The failures exposed `updated_at` bound as text to PostgreSQL `timestamptz`, not skipped tests or flaky outcomes. The three affected SQL sites now cast that parameter explicitly. The corrected selection/staging candidate passes combined Game Design/World full checks, both boot JARs, formatting, Checkstyle, SpotBugs, links and Markdown: 515 Game Design and 246 World unit cases pass, one MinIO case skips, and all 189 PostgreSQL methods skip without Docker. V44 jOOQ generation, Flyway sanity, 230 architecture contracts and workflow/tooling checks pass. The cross-Version request race, exact V43-to-V44 retained-row equality and conflicting-history migration cases compile but have not executed; CI strictly requires all 38 named coordination/selection/graph/fence methods. Five existing PostgreSQL publication-transaction methods retain their rollback, exact readback, immutable release and remap-retention obligations, using explicitly synthetic selection prerequisites for internal mechanics rather than authenticated publication. Account's nine fence cases executed cleanly at the earlier head; World has a separate cross-Version fixture correction and missing graph execution proof. Corrected database execution remains open; no green composed or activation claim follows. Complete Account source-writer/currentness proof, canonical selected-commit participant carriers, synchronized visibility, released-graph readback and lifecycle materialization remain required. The World complete-binding prerequisite includes an explicitly unwired source-qualified current-Version consumer and component proof. Game Design returns its already-persisted canonical Version UUID and complete immutable Version/source provenance from the same read-only snapshot; World reads back the original local pair/source before comparing the exact source, UUID, state and descriptor epoch, preserves the original result on currentness denial, and performs no lifecycle mutation. Exact `e20471d6addc25ebe1e4b3afbc4ac648e116f5de` [CI37254215948](https://github.com/benhook1013/FireMUD/actions/runs/37254215948) has independently verified raw XML for all 29 required PostgreSQL methods: six Game Design complete-binding, eight World pair/currentness, four Game Design owner-snapshot, five version/mTLS (including two identity-composition), and six World identity methods. All 29 executed without skips, failures or errors. The nine existing Game Design owner suites also executed all 63 methods cleanly. The source-built merge `41895db449bef1cd13c98cc178fe80d70caadb35` has the expected `a339` and `e204` parents and the same tree; its raw XML was independently verified. This corrects the earlier `2ceefac830e6747bd088e075d992457f678adde9` checkpoint, where six Game Design complete-binding methods were skipped after World migrations leaked into existing Game Design fixtures. The classes-only dependency repair is now proved, with no pending runtime revalidation for that repair. Earlier local full Game Design/World checks and both boot JARs passed with 709 clean unit executions, one object-store unit skip and all 148 PostgreSQL nodes skipped without Docker. The [World tracker](./world-runtime-and-movement.md#current-status) owns World identity implementation and proof limits. This does not close normal Game Logic publication, canonical World content, commit-time owner/Account fencing or launch activation. 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 981d6e463f..8fc674cf20 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. CI retains raw XML and requires every named fence case to execute without skips; corrected-state database execution remains open. This is not an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. +The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. Independently parsed raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for source `c5fd96e935028b72182d58a611152bee6a8e533b`, records all nine fence methods passing once without skips, errors or failures. Account's Gradle Checks passed, but the job was cancelled at post-Gradle setup; the observer could not retrieve checkout logs while the aggregate remained active, and Game Design and World proof failed separately. These are executed Account storage cases, not a green composed boundary or proof of an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. Exact corrected Account head `3440d4d646414c2c7244e5e0cc1b650cd9e242d8` has executed [CI37290103027](https://github.com/benhook1013/FireMUD/actions/runs/37290103027) proof. Account job `111698347142` succeeded; the strict log records all fourteen `AccountAuthenticationUuidIntegrationTest` cases passing without skips, including one execution of the repaired email-OTP method. No separate OTP XML artifact was uploaded, so that method's attribution rests on the strict job log. All twenty required role/journal/fresh-JOIN/physical-mTLS methods also passed: independently parsed raw suites record JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. The actual Game Session client PostgreSQL/mTLS suite passed 3/3 without skips before its later full check was cancelled; Game Session job `111698347041` and aggregate CI therefore did not pass. The cancellation log supplies no causal explanation. Verified checkout merge `c82c0262d55106fcbea0ed2329adfb1ff19098f1` has the exact World `f968b46adf12570e870b17e17fe0d4382e7078b4` and Account source parents and the same source tree `d39693e551631ed21fb1a6751eb4c4c6658a0e8c`. This closes the OTP fixture execution gap and repeats the physical component proof on that composed tree; upstream caller/policy, current-parent alignment, complete authorization, fresh images, live readiness and activation remain independent gates. 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 bff6df0d0c..0bde5cec8c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains complete immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the revision ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical exact readback does not create another capture after terminal state. The typed ordered REGION plan independently derives both required fence tuples and rejects unsupported or mismatched input; it neither writes content nor authenticates its supplied source binding. The combined four-module check passes, with 242 clean World unit results and all 61 World PostgreSQL nodes compiled but skipped locally without Docker. Graph component fixtures explicitly stipulate six-family and ledger rows in a test-only transaction-local seed scope, restore and assert normal triggers before digest/freeze/capture, and include unchanged V24 canonical-key write-denial proof. They do not prove a canonical content producer; their four graph and eight freeze cases still require runner execution. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. The canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and a numeric alias are not substitutes. +The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. The held-back World mutation algorithm now uses full-tuple, expected-epoch SQL predicates for its declared aggregate and scope advances. An absent epoch can be claimed only from zero with a conflict-safe insert; stale, negative or overflowing expected counters cannot succeed. A losing advance raises `DRAFT_WRITE_CONFLICT` inside the existing owner transaction rather than committing content under an unconditional epoch save. The focused mutation suite executed 29 cases successfully. The consolidated World check, boot JAR, formatting, static analysis, links and Markdown passed with 227 unit executions and no unit skips; all 55 PostgreSQL integration methods, including five new deterministic race, tuple-isolation and rollback cases, compiled but skipped locally without Docker. The subsequent exact-source CI execution is recorded below. This closes a local storage primitive, not complete affected-scope validation, immutable complete-input retry binding, source-qualified content materialization, synchronized Draft visibility, Account authorization, publication or lifecycle. The registered mutation remains denied. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) remains the target contract. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 7999faefc9..cd7acdf272 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -121,6 +121,11 @@ message PublishVersionRequest { string tenant_id = 1; string notes = 2; string publish_request_id = 3; + string version_id = 4; + string expected_version_state_epoch = 5; + string selected_commit_request_id = 6; + string selected_commit_id = 7; + string selected_commit_digest = 8; } message PublishVersionResponse { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java index 5729cbf0a8..31adbd248b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java @@ -54,6 +54,13 @@ public SelectionSnapshot reserve(PublishIntent intent) { requireWritableReadCommittedTransaction(); Objects.requireNonNull(intent, "intent"); + Optional prior = + readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId()); + if (prior.isPresent()) { + requireExactIntent(intent, prior.get().selection().intent()); + return prior.get(); + } + LockedVersion version = coordinator.lockVersionTarget(intent.canonicalTenantId(), intent.canonicalVersionId()); SelectionSnapshot existing = findByTarget(version.target(), false); @@ -82,7 +89,7 @@ public SelectionSnapshot reserve(PublishIntent intent) { } catch (DataAccessException exception) { if (isUniqueConstraintViolation(exception)) { throw new DraftCommitIdentityConflictException( - "An authored Draft publication selection already reserves this Version", exception); + "An authored Draft publication operation already reserves an exact Version", exception); } throw exception; } @@ -99,6 +106,22 @@ public SelectionSnapshot reserve(PublishIntent intent) { return persisted; } + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional readByPublishRequest( + UUID canonicalTenantId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND publish_request_id = ?", + canonicalTenantId, + publishRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + /** Reads the immutable selection only when all canonical target and request fields match. */ public Optional read( UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java index 5cacfc337b..cc68df5fe5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -225,7 +225,7 @@ public OwnerState markOwnerInProgress(DraftCommitBinding binding, Owner owner) { dsl.execute( "UPDATE " + OWNER_RESULT_TABLE - + " SET status = 'IN_PROGRESS', updated_at = ? " + + " SET status = 'IN_PROGRESS', updated_at = CAST(? AS timestamptz) " + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + "AND request_id = ? AND owner = ? AND status = 'NOT_ATTEMPTED'", now(), @@ -278,7 +278,7 @@ public OwnerState recordOwnerOutcome(DraftCommitBinding binding, OwnerOutcome ou "UPDATE " + OWNER_RESULT_TABLE + " SET status = ?, result_commit_id = ?, result_binding_digest = ?, " - + "result_identity = ?, result_bytes = ?, applied_units_json = ?, updated_at = ? " + + "result_identity = ?, result_bytes = ?, applied_units_json = ?, updated_at = CAST(? AS timestamptz) " + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + "AND request_id = ? AND owner = ? AND status = ?", outcome.status().name(), @@ -714,7 +714,7 @@ private void updateWorkflowState(DraftCommitBinding binding, WorkflowState state dsl.execute( "UPDATE " + COMMIT_TABLE - + " SET workflow_state = ?, updated_at = ? " + + " SET workflow_state = ?, updated_at = CAST(? AS timestamptz) " + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + "AND workflow_state <> ?", state.name(), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java index 971991b867..2a1f11f70b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java @@ -2,6 +2,7 @@ import java.time.LocalDateTime; import java.util.List; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -11,8 +12,7 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; public interface VersionService { - VersionDto publishVersion(String tenantId, String notes, String publishRequestId) - throws Exception; + VersionDto publishVersion(PublishIntent intent) throws Exception; VersionDto publishScriptPatchVersion( String tenantId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 6d657e5959..ddce90ac5a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.GameDesignSettingsProtoMapper; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; @@ -226,7 +227,16 @@ public void publishVersion( } VersionDto version = versionService.publishVersion( - request.getTenantId(), request.getNotes(), request.getPublishRequestId()); + new PublishIntent( + canonicalPublicationUuid(request.getTenantId(), "tenant_id"), + canonicalPublicationUuid(request.getVersionId(), "version_id"), + request.getPublishRequestId(), + request.getExpectedVersionStateEpoch(), + request.getNotes(), + canonicalPublicationUuid( + request.getSelectedCommitRequestId(), "selected_commit_request_id"), + canonicalPublicationUuid(request.getSelectedCommitId(), "selected_commit_id"), + request.getSelectedCommitDigest())); builder.setVersionId(version.id()); } catch (AdminAuthorizationException ex) { builder.setError( @@ -251,6 +261,10 @@ public void publishVersion( meterRegistry, logger, "PublishVersion", ex.errorCode(), ex.getMessage())); } catch (IllegalStateException ex) { String errorCode = publishAttemptErrorCode(ex); + if (ex.getMessage() != null + && ex.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")) { + errorCode = "PUBLICATION_AUTHORIZATION_UNAVAILABLE"; + } builder.setError( errorCode == null ? GrpcAppErrors.internal(meterRegistry, logger, "PublishVersion", ex) @@ -2374,6 +2388,14 @@ private void requireSettingsAuthorityReadAccess() { AdminRoleGuard.requireAdminRole(); } + private static UUID canonicalPublicationUuid(String value, String field) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } + private void requireHelpTopicReadAccess() { if (SessionContext.isInternalService()) { return; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index a9ffb64b1d..d92da744bd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -46,7 +47,7 @@ public T executeScriptPatchTransaction(Supplier operation) { } @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) + @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED) public T executeFullVersionTransaction(Supplier operation) { try { return operation.get(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java index 311e104fde..8fe910e37f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java @@ -1,7 +1,18 @@ package net.firedevops.firemud.gamedesign.service.impl; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; + record PublishWorkflowRequest( - String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + String tenantId, + String notes, + String publishRequestId, + String publishWorkflowId, + PublishIntent intent) { + + PublishWorkflowRequest( + String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + this(tenantId, notes, publishRequestId, publishWorkflowId, null); + } /** * Recovers the request id for the legacy command shape that carried only the workflow id. @@ -11,7 +22,10 @@ record PublishWorkflowRequest( * value, and explicit (including blank) request ids are never rewritten. */ PublishWorkflowRequest recoverMissingPublishRequestId() { - if (publishRequestId != null || tenantId == null || publishWorkflowId == null) { + if (intent != null + || publishRequestId != null + || tenantId == null + || publishWorkflowId == null) { return this; } String canonicalPrefix = "publish:" + tenantId + ":publish-request:"; @@ -26,6 +40,7 @@ PublishWorkflowRequest recoverMissingPublishRequestId() { TemporalVersionPublishOrchestrator.workflowId(tenantId, recoveredRequestId))) { return this; } - return new PublishWorkflowRequest(tenantId, notes, recoveredRequestId, publishWorkflowId); + return new PublishWorkflowRequest( + tenantId, notes, recoveredRequestId, publishWorkflowId, intent); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java index 610900ef06..a0f1e53517 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java @@ -7,6 +7,7 @@ import java.time.Duration; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.common.temporal.TemporalTaskQueueResolver; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; @@ -36,10 +37,9 @@ public TemporalVersionPublishOrchestrator( this.commandService = commandService; } - public VersionDto publishFullVersion(String tenantId, String notes, String publishRequestId) { - String workflowId = workflowId(tenantId, publishRequestId); - PublishWorkflowRequest request = - new PublishWorkflowRequest(tenantId, notes, publishRequestId, workflowId); + public VersionDto publishFullVersion(PublishIntent intent) { + PublishWorkflowRequest request = commandService.reserveSelection(intent); + String workflowId = request.publishWorkflowId(); TemporalVersionPublishWorkflow workflow = newWorkflowStub(workflowId); try { WorkflowStub.fromTyped(workflow).start(request); @@ -48,7 +48,7 @@ public VersionDto publishFullVersion(String tenantId, String notes, String publi } PublishWorkflowSnapshot snapshot = waitForSnapshot(workflow, workflowId); if (snapshot.isSucceeded()) { - return commandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); + return commandService.publishFullVersion(request); } throw failureForSnapshot(snapshot); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 5183b3849b..37c057e5f0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -7,15 +7,18 @@ import java.util.Optional; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; -import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.GameRepository; @@ -54,6 +57,7 @@ public class VersionPublishCommandServiceImpl { private final VersionAssetArtifactService versionAssetArtifactService; private final PublishedReleaseBundleService publishedReleaseBundleService; private final RecordedParticipantDigestService recordedParticipantDigestService; + private final AuthoredDraftPublishSelectionRepository authoredSelections; public VersionPublishCommandServiceImpl( VersionRepository versionRepository, @@ -66,7 +70,8 @@ public VersionPublishCommandServiceImpl( ControlPlaneDigestService controlPlaneDigestService, VersionAssetArtifactService versionAssetArtifactService, PublishedReleaseBundleService publishedReleaseBundleService, - RecordedParticipantDigestService recordedParticipantDigestService) { + RecordedParticipantDigestService recordedParticipantDigestService, + AuthoredDraftPublishSelectionRepository authoredSelections) { this.versionRepository = versionRepository; this.gameRepository = gameRepository; this.publishAttemptRepository = publishAttemptRepository; @@ -78,6 +83,35 @@ public VersionPublishCommandServiceImpl( this.versionAssetArtifactService = versionAssetArtifactService; this.publishedReleaseBundleService = publishedReleaseBundleService; this.recordedParticipantDigestService = recordedParticipantDigestService; + this.authoredSelections = authoredSelections; + } + + /** Internal plumbing only: a durable selection does not establish creator authorization. */ + PublishWorkflowRequest reserveSelection(PublishIntent intent) { + try { + return publishAttemptService.executeFullVersionTransaction( + () -> { + AuthoredDraftPublishSelection selection = + authoredSelections.reserve(intent).selection(); + return new PublishWorkflowRequest( + selection.target().gameDesignVersionTenantKey(), + intent.notes(), + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + selection.intent()); + }); + } catch (PublishAttemptService.FullVersionTransactionException exception) { + throw exception.causeException(); + } + } + + VersionDto publishFullVersion(PublishWorkflowRequest request) { + PublishWorkflowSnapshot snapshot = reconcileFullVersionPublish(request); + if (!snapshot.isSucceeded()) { + throw publishFailure(snapshot.failureCode(), snapshot.failureMessage()); + } + return versionMapper.toDto(requireTenantVersion(request.tenantId(), snapshot.versionId())); } public VersionDto publishFullVersion( @@ -94,6 +128,9 @@ public VersionDto publishFullVersion( public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowRequest request) { request = request.recoverMissingPublishRequestId(); validateRequestIdentity(request); + if (request.intent() != null) { + requireSelectedIntent(request); + } logger.info( "Reconciling full-version publish workflow tenant={} workflowId={}", request.tenantId(), @@ -101,6 +138,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { + requireSelectedIntent(request); attempt = reserveDraftAttempt(request); } if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { @@ -119,7 +157,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques emptyIfNull(attempt.getFailureCode()), emptyIfNull(attempt.getFailureMessage())); } - attempt = backfillLegacyFullVersionRequestDigest(request, attempt); + requireSelectedIntent(request); validateFullVersionAttempt(attempt, request); Version version = requireAttemptVersion(attempt, request); @@ -135,6 +173,39 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques throw pendingReconciliation( "pending full-version attempt does not reference a draft version"); } + requireSelectedDraftEpoch(request, version); + requireCanonicalOwnerPublicationCarrier(request); + return reconcileSelectedPublicationMechanics(request); + } + + /** + * Internal selected-attempt recovery mechanics, not a publication authorization entrypoint. + * + *

The workflow entrypoint must establish its owner-carrier boundary before reaching this + * component. Direct fixture invocation stipulates that missing boundary and proves only the + * existing export, transaction and exact-readback mechanics; it never enables public writes. + */ + PublishWorkflowSnapshot reconcileSelectedPublicationMechanics(PublishWorkflowRequest request) { + validateRequestIdentity(request); + requireSelectedIntent(request); + PublishAttempt attempt = + publishAttemptRepository + .findByPublishWorkflowId(request.publishWorkflowId()) + .orElseThrow(() -> pendingReconciliation("selected publish attempt is absent")); + validateFullVersionAttempt(attempt, request); + Version version = requireAttemptVersion(attempt, request); + PublicationReadback existingPublication = readPublication(request, attempt); + if (existingPublication.isComplete()) { + return reconcileCommittedAttempt(request, attempt); + } + if (existingPublication.isPartial()) { + throw pendingReconciliation("selected publication evidence is incomplete"); + } + if (attempt.getStatus() != PublishAttemptStatus.PENDING + || version.getVersionState() != VersionLifecycleState.DRAFT) { + throw pendingReconciliation("selected publication is not the pending Draft operation"); + } + requireSelectedDraftEpoch(request, version); VersionDto dto; List participantDigests; @@ -152,6 +223,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques return failDefinitively(request, attempt, version, null, ex); } try { + assertSelectedCommit(request, participantDigests); publishGateService.assertGatePassed(dto, participantDigests); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { @@ -253,33 +325,36 @@ private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { } private PublishAttempt createDraftAttempt(PublishWorkflowRequest request) { - Game game = - Optional.ofNullable(gameRepository.findByTenantIdForUpdate(request.tenantId())) - .orElseThrow(() -> new IllegalArgumentException("game not found")); + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); Optional existingAttempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()); if (existingAttempt.isPresent()) { + validateFullVersionAttempt(existingAttempt.get(), request); return existingAttempt.get(); } - Version version = new Version(); - version.setTenantId(game.getTenantId()); - version.setNotes(request.notes()); - version.setVersionNumber(calculateNextNumber(request.tenantId())); - version.setVersionState(VersionLifecycleState.DRAFT); - version.setVersionStateEpoch(1L); - version.setUpdatedAt(LocalDateTime.now()); - Version saved = versionRepository.save(version); - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(saved.getId()), request.publishRequestId()); + Version saved = + versionRepository + .findByTenantIdAndIdForUpdate( + selection.target().gameDesignVersionTenantKey(), + selection.target().gameDesignVersionRowId()) + .orElseThrow(() -> new IllegalStateException("Selected authored Version is absent")); + if (saved.isScriptOnly() + || saved.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals( + saved.getVersionStateEpoch(), + Long.parseLong(selection.intent().expectedVersionStateEpoch()))) { + throw new IllegalStateException( + "Selected authored Version is no longer the exact reserved Draft"); + } publishAttemptService.createFullVersionAttempt( - versionMapper.toDto(saved), request.publishWorkflowId(), binding.requestDigest()); + versionMapper.toDto(saved), request.publishWorkflowId(), selection.digest()); return publishAttemptRepository .findByPublishWorkflowId(request.publishWorkflowId()) .orElseThrow(() -> new IllegalStateException("publish attempt not found")); } - private PublishWorkflowSnapshot finalizeFullVersion( + /** Transaction-owned internal mechanic; fixture invocation does not prove owner authorization. */ + PublishWorkflowSnapshot finalizeFullVersion( PublishWorkflowRequest request, List participantDigests, ExportedAssetManifest exportedManifest) { @@ -292,10 +367,12 @@ private PublishWorkflowSnapshot finalizeFullVersion( .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(attempt, request); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - if (!readPublication(request, attempt).isComplete()) { + PublicationReadback readback = readPublication(request, attempt); + if (!readback.isComplete()) { throw pendingReconciliation( "succeeded full-version attempt lacks exact committed release evidence"); } + assertCommittedBundleMayMarkSuccess(request, readback); return succeededSnapshot(attempt); } if (attempt.getStatus() != PublishAttemptStatus.PENDING) { @@ -324,6 +401,9 @@ private PublishWorkflowSnapshot finalizeFullVersion( } VersionDto dto = versionMapper.toDto(version); + requireSelectedDraftEpoch(request, version); + assertSelectedCommit(request, participantDigests); + publishGateService.assertGatePassed(dto, participantDigests); publishAttemptService.recordFullVersionParticipantDigests( request.publishWorkflowId(), participantDigests); VersionAssetArtifactStateDto exportedState = @@ -385,6 +465,9 @@ private PublishWorkflowSnapshot replaySucceededAttempt( } try { requireExactCommittedBundleIdentity(request, attempt, bundle); + if (request.intent() != null) { + assertCommittedBundleMayMarkSuccess(request, readPublication(request, attempt)); + } } catch (RuntimeException ex) { throw pendingReconciliation( "succeeded full-version attempt release bundle identity does not match", ex); @@ -455,6 +538,7 @@ private void assertCommittedBundleMayMarkSuccess( } VersionDto versionDto = versionMapper.toDto(readback.version()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(readback.bundle()); + assertSelectedCommit(request, readback.bundle().participantDigests()); publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); recordedParticipantDigestService.assertMatchesRecordedDigests( request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests()); @@ -540,70 +624,21 @@ private void validateRequestIdentity(PublishWorkflowRequest request) { request.tenantId(), request.publishRequestId()); String expectedWorkflowId = TemporalVersionPublishOrchestrator.workflowId( - request.tenantId(), request.publishRequestId()); + request.intent() == null + ? request.tenantId() + : request.intent().canonicalTenantId().toString(), + request.publishRequestId()); if (!Objects.equals(expectedWorkflowId, request.publishWorkflowId())) { throw new IllegalArgumentException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: publish workflow does not match request identity"); } } - /** - * Repairs only the narrow legacy full-version shape that has an exact current request identity. - * - *

V25 could persist the request-digest column but could not compute a digest in SQL. A legacy - * full-version row is therefore retryable only after this application-side check proves the - * tenant, canonical workflow identity, version id, and version number all agree. Script-patch - * rows intentionally have no equivalent compatibility path: their old workflow identifiers do not - * establish the complete request binding, so ordinary validation continues to fail closed. - */ - private PublishAttempt backfillLegacyFullVersionRequestDigest( - PublishWorkflowRequest request, PublishAttempt attempt) { - if (attempt == null - || attempt.getRequestDigest() != null - || attempt.getPublishType() != PublishType.FULL_VERSION - || !Objects.equals(attempt.getTenantId(), request.tenantId()) - || !Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) - || !Objects.equals( - attempt.getPublishWorkflowId(), - TemporalVersionPublishOrchestrator.workflowId( - request.tenantId(), request.publishRequestId())) - || attempt.getBaseVersionId() != null - || attempt.getScriptPatchVersion() != null - || attempt.getVersionId() == null - || attempt.getVersionNumber() <= 0) { - return attempt; - } - - Optional version = - versionRepository.findByTenantIdAndId(request.tenantId(), attempt.getVersionId()); - if (version.isEmpty() - || !Objects.equals(version.get().getTenantId(), request.tenantId()) - || !Objects.equals(version.get().getId(), attempt.getVersionId()) - || version.get().getVersionNumber() != attempt.getVersionNumber() - || version.get().isScriptOnly()) { - return attempt; - } - - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(attempt.getVersionId()), request.publishRequestId()); - return publishAttemptRepository - .backfillFullVersionRequestDigestIfAbsent( - attempt.getId(), - request.tenantId(), - request.publishWorkflowId(), - attempt.getVersionId(), - attempt.getVersionNumber(), - binding.requestDigest()) - .orElse(attempt); - } - private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowRequest request) { validateFullVersionAttemptIdentity(attempt, request); - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(attempt.getVersionId()), request.publishRequestId()); - if (!Objects.equals(binding.requestDigest(), attempt.getRequestDigest())) { + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (!Objects.equals(selection.target().gameDesignVersionRowId(), attempt.getVersionId()) + || !Objects.equals(selection.digest(), attempt.getRequestDigest())) { throw new IllegalStateException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: full-version request digest does not match request"); } @@ -616,6 +651,10 @@ private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowR */ private void validateTerminalFullVersionAttempt( PublishAttempt attempt, PublishWorkflowRequest request) { + if (request.intent() != null) { + validateFullVersionAttempt(attempt, request); + return; + } validateFullVersionAttemptIdentity(attempt, request); if (attempt.getRequestDigest() == null) { // Legacy terminal attempts predate the digest column. Their canonical workflow identity, @@ -897,12 +936,69 @@ private enum ReadbackState { COMPLETE } - private int calculateNextNumber(String tenantId) { - return versionRepository - .findTopByTenantIdOrderByVersionNumberDesc(tenantId) - .map(Version::getVersionNumber) - .orElse(0) - + 1; + private AuthoredDraftPublishSelection requireSelectedIntent(PublishWorkflowRequest request) { + if (request.intent() == null) { + throw new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: retained terminal readback is the only unselected operation"); + } + AuthoredDraftPublishSelection selection = + authoredSelections + .readByPublishRequest(request.intent().canonicalTenantId(), request.publishRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: exact durable selection is absent")) + .selection(); + if (!selection.intent().equals(request.intent()) + || !selection.target().gameDesignVersionTenantKey().equals(request.tenantId()) + || !selection.intent().notes().equals(request.notes()) + || !selection.intent().publishRequestId().equals(request.publishRequestId())) { + throw new IllegalStateException( + "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: exact original selection intent differs"); + } + return selection; + } + + private void requireCanonicalOwnerPublicationCarrier(PublishWorkflowRequest request) { + if (request.intent() != null) { + // Existing digest clients carry private tenant keys and numeric Version selectors. They + // cannot authenticate/freeze/materialize this selected canonical UUID commit. Do not + // rewrite its workflow identity to fit that incomplete owner boundary. + throw new IllegalStateException( + "PUBLISH_OWNER_CARRIER_UNAVAILABLE: canonical selected-commit owner freeze and materialization are required"); + } + } + + private void requireSelectedDraftEpoch(PublishWorkflowRequest request, Version version) { + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (!Objects.equals( + version.getVersionStateEpoch(), + Long.parseLong(selection.intent().expectedVersionStateEpoch()))) { + throw new IllegalStateException( + "VERSION_STATE_EPOCH_STALE: Draft differs from its exact original publication selection"); + } + } + + private void assertSelectedCommit( + PublishWorkflowRequest request, List digests) { + if (request.intent() == null) { + return; // Historical terminal readback does not invent missing selection evidence. + } + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (digests == null + || digests.stream() + .anyMatch( + digest -> + digest == null + || !selection + .selectedCommit() + .commitId() + .toString() + .equals(digest.appliedCommitId()))) { + throw new PublishGateFailureException( + PublishGateFailureCode.APPLIED_COMMIT_MISMATCH, + "Every participant must report the exact selected authored Draft commit"); + } } private PublishedReleaseBundleDto readPublishedReleaseBundle(String tenantId, long versionId) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 24e1aa9c90..94744ff0db 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -120,15 +121,12 @@ public VersionServiceImpl( @Override @Timed(value = "gamedesign.version.publish") - public VersionDto publishVersion(String tenantId, String notes, String publishRequestId) { - logger.info("Publishing version for tenant {}", tenantId); - PublicationDigestRequestBinding.validatePublicationIdentity(tenantId, publishRequestId); - TemporalVersionPublishOrchestrator orchestrator = - temporalPublishOrchestrator.orElseThrow( - () -> - new IllegalStateException( - "PUBLISH_WORKFLOW_UNAVAILABLE: durable publication workflow is required")); - return orchestrator.publishFullVersion(tenantId, notes, publishRequestId); + public VersionDto publishVersion(PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + // Account's authenticated actor/role/party/terms producer and complete authenticated owner + // freeze/materialization are unavailable. Selection storage is not commit authorization. + throw new IllegalStateException( + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: exact current Account authorization and owner freeze are required"); } @Override diff --git a/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql new file mode 100644 index 0000000000..6ea648cf2f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql @@ -0,0 +1,5 @@ +-- A publication operation selects one exact Version in its canonical tenant. +-- Conflicting retained reservations deliberately fail migration; no history is discarded. +ALTER TABLE game_design_authored_draft_publish_selection + ADD CONSTRAINT uq_gd_authored_draft_publish_operation + UNIQUE (canonical_tenant_id, publish_request_id); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java index 96fd0ec62b..542e82cc86 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java @@ -36,6 +36,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -66,6 +67,182 @@ static void setUpSchema() { fixture = createFixture(); } + @Test + void v44PreservesExactSelectionsRetainedAtV43() { + Fixture retained = createFixture("43"); + VersionFixture first = retained.newVersion(Long.parseLong(LARGE_EPOCH)); + VersionFixture second = retained.newFullVersionInTenant(first); + VersionFixture otherTenant = retained.newVersion(1L); + DraftCommitBinding firstCommit = binding(first.target(), UUID.randomUUID(), UUID.randomUUID()); + DraftCommitBinding secondCommit = + binding(second.target(), UUID.randomUUID(), UUID.randomUUID()); + DraftCommitBinding otherCommit = + binding(otherTenant.target(), UUID.randomUUID(), UUID.randomUUID()); + retained.synchronize(firstCommit); + retained.synchronize(secondCommit); + retained.synchronize(otherCommit); + PublishIntent firstIntent = intent(first, firstCommit, "retained notes \"quoted\"\n世界"); + PublishIntent secondIntent = intent(second, secondCommit, "second retained selection"); + PublishIntent otherIntent = + sameRequestIntent(otherTenant, otherCommit, firstIntent.publishRequestId()); + SelectionSnapshot firstSelection = reserve(retained, firstIntent); + SelectionSnapshot secondSelection = reserve(retained, secondIntent); + SelectionSnapshot otherSelection = reserve(retained, otherIntent); + List> before = retainedSelectionRows(retained); + assertThat(before).hasSize(3); + + migrate(retained.dataSource(), retained.schema(), "44"); + + assertThat(retainedSelectionRows(retained)).isEqualTo(before); + assertRetainedSelection(retained, firstSelection); + assertRetainedSelection(retained, secondSelection); + assertRetainedSelection(retained, otherSelection); + assertThat(reserve(retained, firstIntent)).isEqualTo(firstSelection); + assertThat(reserve(retained, secondIntent)).isEqualTo(secondSelection); + assertThat(reserve(retained, otherIntent)).isEqualTo(otherSelection); + assertThat(retainedSelectionRows(retained)).isEqualTo(before); + assertThat( + retained + .dsl() + .fetchCount(DSL.table(DSL.name(FLYWAY_TABLE)), DSL.field("version").eq("44"))) + .isEqualTo(1); + } + + @Test + void v44RejectsConflictingRetainedRequestAcrossVersionsWithoutDiscardingEitherHistory() { + Fixture retained = createFixture("43"); + VersionFixture first = retained.newVersion(1L); + VersionFixture second = retained.newFullVersionInTenant(first); + DraftCommitBinding firstCommit = binding(first.target(), UUID.randomUUID(), UUID.randomUUID()); + DraftCommitBinding secondCommit = + binding(second.target(), UUID.randomUUID(), UUID.randomUUID()); + retained.synchronize(firstCommit); + retained.synchronize(secondCommit); + PublishIntent firstIntent = intent(first, firstCommit, "first retained history"); + PublishIntent secondIntent = + sameRequestIntent(second, secondCommit, firstIntent.publishRequestId()); + SelectionSnapshot firstSelection = reserve(retained, firstIntent); + // V43 permitted this exact tenant/request reuse across Versions. The current repository + // prevents it, so insert the historically valid second selection under V43's real triggers. + insertPreV44Selection(retained, second, secondIntent); + SelectionSnapshot secondSelection = + retained + .selections() + .read( + secondIntent.canonicalTenantId(), + secondIntent.canonicalVersionId(), + secondIntent.publishRequestId()) + .orElseThrow(); + List> before = retainedSelectionRows(retained); + assertThat(before).hasSize(2); + + assertThatThrownBy(() -> migrate(retained.dataSource(), retained.schema(), "44")) + .isInstanceOf(FlywayException.class) + .hasMessageContaining("uq_gd_authored_draft_publish_operation"); + + assertThat(retainedSelectionRows(retained)).isEqualTo(before); + assertRetainedTargetSelection(retained, firstSelection); + assertRetainedTargetSelection(retained, secondSelection); + assertThat( + retained + .dsl() + .fetchCount(DSL.table(DSL.name(FLYWAY_TABLE)), DSL.field("version").eq("44"))) + .isZero(); + assertThat( + retained + .dsl() + .fetchCount(DSL.table(DSL.name(FLYWAY_TABLE)), DSL.field("version").eq("43"))) + .isEqualTo(1); + } + + private static SelectionSnapshot reserve(Fixture retained, PublishIntent intent) { + return Objects.requireNonNull( + retained.ownerTransaction().execute(status -> retained.selections().reserve(intent))); + } + + private static List> retainedSelectionRows(Fixture retained) { + return retained + .dsl() + .fetch( + "SELECT * FROM game_design_authored_draft_publish_selection " + + "ORDER BY canonical_tenant_id, canonical_version_id") + .intoMaps(); + } + + private static void assertRetainedSelection(Fixture retained, SelectionSnapshot expected) { + assertRetainedTargetSelection(retained, expected); + PublishIntent intent = expected.selection().intent(); + assertThat( + retained + .selections() + .readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId())) + .contains(expected); + } + + private static void assertRetainedTargetSelection(Fixture retained, SelectionSnapshot expected) { + PublishIntent intent = expected.selection().intent(); + SelectionSnapshot actual = + retained + .selections() + .read( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()) + .orElseThrow(); + assertThat(actual).isEqualTo(expected); + assertThat(actual.selection().canonicalBytes()) + .containsExactly(expected.selection().canonicalBytes()); + assertThat(actual.selection().digest()).isEqualTo(expected.selection().digest()); + assertThat(actual.createdAt()).isEqualTo(expected.createdAt()); + } + + private static void insertPreV44Selection( + Fixture retained, VersionFixture version, PublishIntent intent) { + retained + .ownerTransaction() + .executeWithoutResult( + status -> { + retained + .coordinator() + .lockVersionTarget(intent.canonicalTenantId(), intent.canonicalVersionId()); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, + version.target(), + retained + .coordinator() + .requireSynchronizedPublicationEvidence( + version.target(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest())); + TargetProof target = selection.target(); + assertThat( + retained + .dsl() + .execute( + "INSERT INTO game_design_authored_draft_publish_selection " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, publish_request_id, version_state_epoch, " + + "selected_commit_request_id, selected_commit_id, selected_commit_digest, " + + "selection_digest, selection_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selection.digest(), + selection.canonicalJson())) + .isEqualTo(1); + }); + } + @Test void reusesExistingAuthoredVersionAndExactReplayIgnoresLaterServerState() { VersionFixture version = fixture.newVersion(Long.parseLong(LARGE_EPOCH)); @@ -221,6 +398,98 @@ void failedReservationTransactionLeavesNoSelection() { .isEmpty(); } + @Test + void samePublicationRequestCannotSelectAnotherVersionInTheSameTenant() { + VersionFixture first = fixture.newVersion(1L); + VersionFixture second = fixture.newFullVersionInTenant(first); + DraftCommitBinding firstCommit = binding(first.target(), UUID.randomUUID(), UUID.randomUUID()); + DraftCommitBinding secondCommit = + binding(second.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(firstCommit); + fixture.synchronize(secondCommit); + PublishIntent original = intent(first, firstCommit, "selected notes"); + PublishIntent changed = sameRequestIntent(second, secondCommit, original.publishRequestId()); + SelectionSnapshot retained = inTransaction(() -> fixture.selections().reserve(original)); + + assertThatThrownBy(() -> inTransaction(() -> fixture.selections().reserve(changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThat( + fixture + .selections() + .readByPublishRequest(original.canonicalTenantId(), original.publishRequestId())) + .contains(retained); + assertThat( + fixture + .selections() + .read( + changed.canonicalTenantId(), + changed.canonicalVersionId(), + changed.publishRequestId())) + .isEmpty(); + } + + @Test + void concurrentPublicationRequestClaimsAcrossVersionsRetainOnlyOneSelection() throws Exception { + VersionFixture first = fixture.newVersion(1L); + VersionFixture second = fixture.newFullVersionInTenant(first); + DraftCommitBinding firstCommit = binding(first.target(), UUID.randomUUID(), UUID.randomUUID()); + DraftCommitBinding secondCommit = + binding(second.target(), UUID.randomUUID(), UUID.randomUUID()); + fixture.synchronize(firstCommit); + fixture.synchronize(secondCommit); + String requestId = "racing-publication-" + UUID.randomUUID(); + PublishIntent firstIntent = sameRequestIntent(first, firstCommit, requestId); + PublishIntent secondIntent = sameRequestIntent(second, secondCommit, requestId); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future firstClaim = + executor.submit(() -> claimRacingIntent(firstIntent, ready, start)); + Future secondClaim = + executor.submit(() -> claimRacingIntent(secondIntent, ready, start)); + await(ready); + start.countDown(); + assertThat(firstClaim.get(20, TimeUnit.SECONDS)) + .isNotEqualTo(secondClaim.get(20, TimeUnit.SECONDS)); + SelectionSnapshot retained = + fixture + .selections() + .readByPublishRequest(firstIntent.canonicalTenantId(), requestId) + .orElseThrow(); + assertThat(retained.selection().intent()).isIn(firstIntent, secondIntent); + assertThat(inTransaction(() -> fixture.selections().reserve(retained.selection().intent()))) + .isEqualTo(retained); + } finally { + executor.shutdownNow(); + } + } + + private static boolean claimRacingIntent( + PublishIntent intent, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + try { + inTransaction(() -> fixture.selections().reserve(intent)); + return true; + } catch (DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException expected) { + return false; + } + } + + private static PublishIntent sameRequestIntent( + VersionFixture version, DraftCommitBinding commit, String requestId) { + return new PublishIntent( + version.target().canonicalTenantId(), + version.target().canonicalVersionId(), + requestId, + version.stateEpoch(), + "selected notes", + commit.requestId(), + commit.commitId(), + commit.digest()); + } + @Test void versionRowLockSerializesSelectionAgainstApplicationSlotClaim() throws Exception { VersionFixture version = fixture.newVersion(1L); @@ -469,21 +738,17 @@ private static OwnerOutcome appliedOutcome(DraftCommitBinding binding) { } private static Fixture createFixture() { + return createFixture(null); + } + + private static Fixture createFixture(String migrationTarget) { String schema = "gd_draft_select_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(POSTGRES.getJdbcUrl()); dataSource.setUsername(POSTGRES.getUsername()); dataSource.setPassword(POSTGRES.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table(FLYWAY_TABLE) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + migrate(dataSource, schema, migrationTarget); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transaction = @@ -494,7 +759,24 @@ private static Fixture createFixture() { DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); AuthoredDraftPublishSelectionRepository selections = new AuthoredDraftPublishSelectionRepository(dsl, coordinator); - return new Fixture(dsl, transaction, games, versions, coordinator, selections); + return new Fixture( + schema, dataSource, dsl, transaction, games, versions, coordinator, selections); + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, String migrationTarget) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (migrationTarget != null) { + configuration.target(migrationTarget); + } + configuration.load().migrate(); } private static T inTransaction(Supplier work) { @@ -528,6 +810,8 @@ private static String sha256(String value) { private record VersionFixture(TargetProof target, long rowId, String stateEpoch) {} private record Fixture( + String schema, + DriverManagerDataSource dataSource, DSLContext dsl, TransactionTemplate ownerTransaction, GameRepository games, @@ -567,6 +851,17 @@ VersionFixture newScriptOnlyVersion(VersionFixture base) { return new VersionFixture(target(savedVersion), savedVersion.getId(), "1"); } + VersionFixture newFullVersionInTenant(VersionFixture base) { + Version version = new Version(); + version.setTenantId(base.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version saved = + Objects.requireNonNull(ownerTransaction.execute(status -> versions.save(version))); + return new VersionFixture(target(saved), saved.getId(), "1"); + } + void synchronize(DraftCommitBinding binding) { ownerTransaction.executeWithoutResult( status -> { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index e40054aecb..4ec8ffb127 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -2,14 +2,29 @@ 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 java.lang.reflect.Constructor; import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.List; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; @@ -19,6 +34,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.entity.VersionTemplateRemapSet; +import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.model.PublishType; @@ -47,6 +63,7 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.ReflectionTestUtils; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -89,10 +106,12 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; + @Autowired private VersionMapper versionMapper; @Autowired private VersionAssetExportCandidateService versionAssetExportCandidateService; @Autowired private VersionAssetPublicationService versionAssetPublicationService; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; @Autowired private DSLContext dsl; + @MockitoBean private AuthoredDraftPublishSelectionRepository authoredSelectionRepository; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @@ -344,18 +363,12 @@ void recordsAndIndependentlyReadsDedicatedAbilitySchemaDigestOnPublishAttempt() @Test void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { - String tenantId = "9002"; - String publishRequestId = "successful-reconcile-request"; - String publishWorkflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - tenantId, - "publish-request", - publishRequestId); - Game game = new Game(); - game.setTenantId(tenantId); - game.setName("successful-transaction-proof-game"); - gameRepository.save(game); + SelectedDraftFixture fixture = + createSelectedDraftFixture( + "successful-transaction-proof-game", 1, "successful transaction proof"); + String tenantId = fixture.tenantId(); + String publishRequestId = fixture.publishRequestId(); + String publishWorkflowId = fixture.publishWorkflowId(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -369,7 +382,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", String.valueOf(version.id()), - "version:" + version.id(), + fixture.selection().selectedCommit().commitId().toString(), "transaction-proof-design-digest", 1, null, @@ -386,41 +399,43 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth new ExportedAssetManifest(FINALIZATION_MANIFEST_HASH, 1, List.of(), List.of())); }); - VersionDto publishedVersion = - versionPublishCommandService.publishFullVersion( - tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + Object publication = invokeSelectedPublicationMechanics(fixture); + assertThat((Boolean) ReflectionTestUtils.invokeMethod(publication, "isSucceeded")).isTrue(); + assertThat((Long) ReflectionTestUtils.invokeMethod(publication, "versionId")) + .isEqualTo(fixture.version().getId()); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); Version storedVersion = - versionRepository.findByTenantIdAndId(tenantId, publishedVersion.id()).orElseThrow(); + versionRepository.findByTenantIdAndId(tenantId, fixture.version().getId()).orElseThrow(); PublishedReleaseBundle bundle = publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow(); VersionAssetArtifact artifact = versionAssetArtifactRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow(); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); - assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); + assertThat(attempt.getVersionId()).isEqualTo(fixture.version().getId()); + assertThat(attempt.getRequestDigest()).isEqualTo(fixture.selection().digest()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); assertThat(bundle.getManifestHash()).isEqualTo(FINALIZATION_MANIFEST_HASH); assertThat(bundle.getPublishedReleaseBundleRef()).isNotBlank(); assertThat(bundle.getPublishedReleaseBundleRef()) .isNotEqualTo( - "release-bundle:" + tenantId + ":" + publishedVersion.id() + ":" + bundle.getId()); + "release-bundle:" + tenantId + ":" + fixture.version().getId() + ":" + bundle.getId()); PublishedReleaseBundle durableBundle = publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow(); assertThat(durableBundle.getPublishedReleaseBundleRef()) .isEqualTo(bundle.getPublishedReleaseBundleRef()); PublishedReleaseBundle changedReference = publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow(); changedReference.setPublishedReleaseBundleRef("replacement-opaque-release-reference"); assertThatThrownBy(() -> publishedReleaseBundleRepository.save(changedReference)) @@ -428,7 +443,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .hasMessageContaining("Published release bundle is immutable"); PublishedReleaseBundle changedTuple = publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow(); changedTuple.setManifestHash("changed-manifest"); assertThatThrownBy(() -> publishedReleaseBundleRepository.save(changedTuple)) @@ -444,23 +459,23 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .hasStackTraceContaining("published release bundle attestation is immutable"); assertThat( publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow() .getPublishedReleaseBundleRef()) .isEqualTo(bundle.getPublishedReleaseBundleRef()); assertThat( publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow() .getManifestHash()) .isEqualTo(FINALIZATION_MANIFEST_HASH); String generationConfigRevision = bundle.getGenerationConfigRevision(); assertThat(generationConfigRevision.length()).isGreaterThan(128); - versionPublishCommandService.publishFullVersion( - tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + Object replay = invokeSelectedPublicationReplay(fixture); + assertThat((Boolean) ReflectionTestUtils.invokeMethod(replay, "isSucceeded")).isTrue(); assertThat( publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, fixture.version().getId()) .orElseThrow() .getGenerationConfigRevision()) .isEqualTo(generationConfigRevision); @@ -470,18 +485,11 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth @Test void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet() { - String tenantId = "9003"; - String publishRequestId = "failed-remap-request"; - String publishWorkflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - tenantId, - "publish-request", - publishRequestId); Game game = new Game(); - game.setTenantId(tenantId); + game.setTenantId(UUID.randomUUID().toString()); game.setName("failed-remap-proof-game"); - gameRepository.save(game); + Game savedGame = gameRepository.save(game); + String tenantId = savedGame.getTenantId(); Version sourceVersion = new Version(); sourceVersion.setTenantId(tenantId); @@ -491,6 +499,9 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( sourceVersion.setNotes("remap source"); sourceVersion = versionRepository.save(sourceVersion); long sourceVersionId = sourceVersion.getId(); + SelectedDraftFixture fixture = createSelectedDraftFixture(savedGame, 2, "failed remap proof"); + String publishRequestId = fixture.publishRequestId(); + String publishWorkflowId = fixture.publishWorkflowId(); AtomicReference candidateVersionId = new AtomicReference<>(); AtomicReference candidateVersionNumber = new AtomicReference<>(); AtomicReference exportedVersionNumber = new AtomicReference<>(); @@ -515,7 +526,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", String.valueOf(candidate.id()), - "version:" + candidate.id(), + fixture.selection().selectedCommit().commitId().toString(), "failed-remap-design-digest", 1, null, @@ -578,13 +589,11 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.eq(publishWorkflowId), Mockito.eq(exportedManifest.manifestHash())); - Throwable publishFailure = - catchThrowable( - () -> - versionPublishCommandService.publishFullVersion( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)); - - assertThat(publishFailure).isInstanceOf(RuntimeException.class); + Object failedPublication = invokeSelectedPublicationMechanics(fixture); + assertThat((Boolean) ReflectionTestUtils.invokeMethod(failedPublication, "isSucceeded")) + .isFalse(); + assertThat((String) ReflectionTestUtils.invokeMethod(failedPublication, "failureMessage")) + .isEqualTo(longFailureMessage); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); String failureContext = @@ -607,9 +616,9 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( + ", exportCallbackFailureFrame=" + firstStackFrame(exportCallbackFailure.get()) + ", failure=" - + publishFailure.getClass().getName() + + failedPublication.getClass().getName() + ": " - + publishFailure.getMessage() + + ReflectionTestUtils.invokeMethod(failedPublication, "failureMessage") + ")"; assertThat(exportCompleted.get()).as(failureContext).isTrue(); assertThat(finalizationFailureInjected.get()).as(failureContext).isTrue(); @@ -647,16 +656,14 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(retainedRemapSet.getSourceVersionId()).isEqualTo(sourceVersionId); assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); - assertThatThrownBy( - () -> - versionPublishCommandService.publishFullVersion( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)) + assertThatThrownBy(() -> invokeSelectedPublicationCommand(fixture)) .isInstanceOf(IllegalStateException.class) .hasMessage(longFailureMessage); PublishAttempt replayedAttempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); assertThat(replayedAttempt).isEqualTo(attempt); assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(replayedAttempt.getRequestDigest()).isEqualTo(fixture.selection().digest()); assertThat(replayedAttempt.getVersionId()).isEqualTo(candidateVersionId.get()); assertThat(replayedAttempt.getVersionNumber()).isEqualTo(candidateVersionNumber.get()); assertThat(replayedAttempt.getFailureCode()).isEqualTo(attempt.getFailureCode()); @@ -673,6 +680,153 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .exportAssets(Mockito.eq(tenantId), Mockito.anyInt()); } + private SelectedDraftFixture createSelectedDraftFixture( + String gameName, int versionNumber, String notes) { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName(gameName); + return createSelectedDraftFixture(gameRepository.save(game), versionNumber, notes); + } + + /** + * Stipulates synthetic exact selection evidence for the internal transaction-mechanics fixture. + * The repository and current-owner publication-carrier boundary are intentionally not proved. + */ + private SelectedDraftFixture createSelectedDraftFixture( + Game game, int versionNumber, String notes) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes(notes); + Version savedVersion = versionRepository.save(version); + + TargetProof target = + new TargetProof( + game.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW"); + String publishRequestId = UUID.randomUUID().toString(); + UUID selectedCommitRequestId = UUID.randomUUID(); + UUID selectedCommitId = UUID.randomUUID(); + List revisions = + java.util.stream.IntStream.range(0, Owner.values().length) + .mapToObj( + index -> + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.values()[index], + "{\"fixture\":\"transaction-proof\"}")) + .toList(); + List affectedUnits = + java.util.Arrays.stream(Owner.values()) + .map( + owner -> + new AffectedUnit( + owner, + "VERSION", + savedVersion.getCanonicalVersionId().toString(), + "VERSION", + savedVersion.getCanonicalVersionId().toString(), + "1")) + .toList(); + DraftCommitBinding selectedCommit = + DraftCommitBinding.create( + target, + selectedCommitRequestId, + selectedCommitId, + UUID.randomUUID().toString(), + revisions, + affectedUnits); + PublishIntent intent = + new PublishIntent( + game.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + publishRequestId, + savedVersion.getVersionStateEpoch().toString(), + notes, + selectedCommitRequestId, + selectedCommitId, + selectedCommit.digest()); + VisibilityFence visibilityFence = + new VisibilityFence( + target, + selectedCommitRequestId, + selectedCommitId, + selectedCommit.digest(), + "[]", + OffsetDateTime.now(ZoneOffset.UTC)); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(selectedCommit, visibilityFence)); + Mockito.when( + authoredSelectionRepository.readByPublishRequest( + game.getCanonicalTenantId(), publishRequestId)) + .thenReturn( + Optional.of(new SelectionSnapshot(selection, OffsetDateTime.now(ZoneOffset.UTC)))); + + String workflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + game.getCanonicalTenantId().toString(), + "publish-request", + publishRequestId); + publishAttemptService.createFullVersionAttempt( + versionMapper.toDto(savedVersion), workflowId, selection.digest()); + return new SelectedDraftFixture( + game.getTenantId(), notes, publishRequestId, workflowId, savedVersion, selection); + } + + private Object invokeSelectedPublicationMechanics(SelectedDraftFixture fixture) { + return ReflectionTestUtils.invokeMethod( + versionPublishCommandService, + "reconcileSelectedPublicationMechanics", + workflowRequest(fixture)); + } + + private Object invokeSelectedPublicationReplay(SelectedDraftFixture fixture) { + return ReflectionTestUtils.invokeMethod( + versionPublishCommandService, "reconcileFullVersionPublish", workflowRequest(fixture)); + } + + private Object invokeSelectedPublicationCommand(SelectedDraftFixture fixture) { + return ReflectionTestUtils.invokeMethod( + versionPublishCommandService, "publishFullVersion", workflowRequest(fixture)); + } + + private Object workflowRequest(SelectedDraftFixture fixture) { + try { + Class requestType = + Class.forName("net.firedevops.firemud.gamedesign.service.impl.PublishWorkflowRequest"); + Constructor constructor = + requestType.getDeclaredConstructor( + String.class, String.class, String.class, String.class, PublishIntent.class); + constructor.setAccessible(true); + return constructor.newInstance( + fixture.tenantId(), + fixture.notes(), + fixture.publishRequestId(), + fixture.publishWorkflowId(), + fixture.selection().intent()); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("Internal publication request type is unavailable", exception); + } + } + + private record SelectedDraftFixture( + String tenantId, + String notes, + String publishRequestId, + String publishWorkflowId, + Version version, + AuthoredDraftPublishSelection selection) {} + private static String firstStackFrame(Throwable failure) { if (failure == null || failure.getStackTrace().length == 0) { return "none"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 56bf298d40..ec01570132 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; @@ -401,107 +402,196 @@ void getPublishedScriptPatchVersionRejectsMissingBaseScope() { } @Test - void publishVersionRequiresPublishRequestId() { + void publishVersionWithoutAuthenticatedActorIsDeniedBeforeServiceCall() { + AtomicReference ref = new AtomicReference<>(); + + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); + } + + @Test + void publishVersionRequiresStableRequestIdBeforeServiceCall() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { service.publishVersion( - PublishVersionRequest.newBuilder().setTenantId("tenant-1").setNotes("notes").build(), + publishRequest("publish-request-1").setPublishRequestId("").build(), observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); + } + + @Test + void publishVersionRejectsMalformedCanonicalSelectionBeforeServiceCall() { + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion( + publishRequest("publish-request-1").setSelectedCommitId("not-a-uuid").build(), observerFor(ref)); } assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); + } + + @Test + void publishVersionRejectsMalformedOrNonPositiveExpectedStateEpochBeforeServiceCall() { + for (String epoch : List.of("0", "not-an-epoch")) { + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion( + publishRequest("publish-request-1").setExpectedVersionStateEpoch(epoch).build(), + observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + } + + Mockito.verifyNoInteractions(versionService); } @Test - void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + void publishVersionMapsOwnerAuthorizationUnavailableWithoutTreatingItAsSuccess() + throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) .thenThrow( new IllegalStateException( - "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match")); + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: current Account owner proof is absent")); AtomicReference ref = new AtomicReference<>(); + // This bypasses only the outer transport role guard so the service error mapping is tested. try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); } - assertEquals("PUBLISH_ATTEMPT_SCOPE_MISMATCH", ref.get().getError().getCode()); + assertEquals("PUBLICATION_AUTHORIZATION_UNAVAILABLE", ref.get().getError().getCode()); + } + + @Test + void publishVersionMapsKnownAttemptIdentityFailure() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow( + new IllegalArgumentException("PUBLISH_ATTEMPT_IDENTITY_CONFLICT: request changed")); + AtomicReference ref = new AtomicReference<>(); + + // Transport fixture only; this is not an authorized publication fixture. + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + } + + assertEquals("PUBLISH_ATTEMPT_IDENTITY_CONFLICT", ref.get().getError().getCode()); } @Test void publishVersionMapsUnavailableWorkflowWithoutHidingItAsInternal() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) .thenThrow( new IllegalStateException("PUBLISH_WORKFLOW_UNAVAILABLE: Temporal is unavailable")); AtomicReference ref = new AtomicReference<>(); + // Transport fixture only; it does not exercise or authorize the public owner boundary. try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); } assertEquals("PUBLISH_WORKFLOW_UNAVAILABLE", ref.get().getError().getCode()); } @Test - void publishVersionMapsTemporalKnownGateFailureCode() throws Exception { - PublishGateFailureException gateFailure = - (PublishGateFailureException) - TemporalVersionPublishOrchestrator.failureForSnapshot( - new PublishWorkflowSnapshot( - 0L, - 0, - "publish:tenant-1:publish-request:publish-request-1", - "FAILED", - PublishGateFailureCode.PARTICIPANT_SET_MISMATCH.name(), - "participant set mismatch")); - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) - .thenThrow(gateFailure); + void publishVersionMapsKnownAttemptStateFailure() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow(new IllegalStateException("PUBLISH_ATTEMPT_INCONSISTENT: state differs")); AtomicReference ref = new AtomicReference<>(); + // Transport fixture only; this does not supply owner authorization or selected proof. try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + } + + assertEquals("PUBLISH_ATTEMPT_INCONSISTENT", ref.get().getError().getCode()); + } + + @Test + void publishVersionMapsKnownAttemptScopeFailure() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow( + new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced Version differs")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + } + + assertEquals("PUBLISH_ATTEMPT_SCOPE_MISMATCH", ref.get().getError().getCode()); + } + + @Test + void publishVersionMapsTypedGateFailure() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow( + new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_SET_MISMATCH, "participant set mismatch")); + AtomicReference ref = new AtomicReference<>(); + + // Transport fixture only; gate mapping does not establish current owner authorization. + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); } assertEquals("PARTICIPANT_SET_MISMATCH", ref.get().getError().getCode()); } @Test - void publishVersionMapsKnownIllegalArgumentPublishAttemptCode() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + void publishVersionMapsPendingReconciliationToStableCode() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) .thenThrow( - new IllegalArgumentException( - "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: publish workflow does not match request")); + new VersionPublishCommandServiceImpl.PendingReconciliationException( + "selected release readback is incomplete")); AtomicReference ref = new AtomicReference<>(); + // Transport fixture only; a real public caller remains denied before this service path. try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); } - assertEquals("PUBLISH_ATTEMPT_IDENTITY_CONFLICT", ref.get().getError().getCode()); + assertEquals("PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED", ref.get().getError().getCode()); + } + + @Test + void publishVersionMapsTypedPendingReconciliationToStableApplicationError() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow(new PublishAttemptPendingReconciliationException()); + AtomicReference ref = new AtomicReference<>(); + + // Transport fixture only; a real public caller still requires current Account and owner proof. + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + } + + assertEquals( + PublishAttemptPendingReconciliationException.ERROR_CODE, ref.get().getError().getCode()); + assertEquals( + PublishAttemptPendingReconciliationException.SAFE_MESSAGE, + ref.get().getError().getMessage()); + } + + @Test + void publishVersionMapsUnknownIllegalStateToInternal() throws Exception { + Mockito.when(versionService.publishVersion(Mockito.any(PublishIntent.class))) + .thenThrow(new IllegalStateException("unexpected internal failure")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(publishRequest("publish-request-1").build(), observerFor(ref)); + } + + assertEquals("INTERNAL", ref.get().getError().getCode()); } @Test @@ -622,25 +712,6 @@ void publishScriptPatchVersionMapsUnknownIllegalArgumentToInvalidArgument() thro assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } - @Test - void publishVersionKeepsUnknownIllegalStateFailuresInternal() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) - .thenThrow(new IllegalStateException("unexpected internal state")); - AtomicReference ref = new AtomicReference<>(); - - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); - } - - assertEquals("INTERNAL", ref.get().getError().getCode()); - } - @Test void publishScriptPatchVersionKeepsUnknownIllegalStateFailuresInternal() throws Exception { Mockito.when( @@ -690,29 +761,6 @@ void publishScriptPatchVersionMapsReplayedFailureCodeAndMessage() throws Excepti assertEquals("stored identity cannot be replayed", ref.get().getError().getMessage()); } - @Test - void publishVersionMapsPendingReconciliationToStableApplicationError() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "request-1")) - .thenThrow(new PublishAttemptPendingReconciliationException()); - AtomicReference ref = new AtomicReference<>(); - - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("request-1") - .build(), - observerFor(ref)); - } - - assertEquals( - PublishAttemptPendingReconciliationException.ERROR_CODE, ref.get().getError().getCode()); - assertEquals( - PublishAttemptPendingReconciliationException.SAFE_MESSAGE, - ref.get().getError().getMessage()); - } - @Test void publishScriptPatchVersionMapsPendingReconciliationToStableApplicationError() throws Exception { @@ -1729,6 +1777,31 @@ private static PublishedArtifactDigest logoProof() { 1); } + private PublishIntent publishIntent(String requestId) { + return new PublishIntent( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + requestId, + "9", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); + } + + private PublishVersionRequest.Builder publishRequest(String requestId) { + PublishIntent intent = publishIntent(requestId); + return PublishVersionRequest.newBuilder() + .setTenantId(intent.canonicalTenantId().toString()) + .setVersionId(intent.canonicalVersionId().toString()) + .setNotes(intent.notes()) + .setPublishRequestId(intent.publishRequestId()) + .setExpectedVersionStateEpoch(intent.expectedVersionStateEpoch()) + .setSelectedCommitRequestId(intent.selectedCommitRequestId().toString()) + .setSelectedCommitId(intent.selectedCommitId().toString()) + .setSelectedCommitDigest(intent.selectedCommitDigest()); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java new file mode 100644 index 0000000000..07579ab94c --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.OffsetDateTime; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.mapper.VersionMapper; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportService; +import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.PublishAttemptService; +import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; + +/** Explicit internal fixtures establish plumbing only, never Account or owner authorization. */ +class SelectedAuthoredDraftPublishWorkflowTest { + @Test + void reservationCarriesOriginalIntentWithCanonicalWorkflowAndServerResolvedRowScope() { + Fixture f = new Fixture(); + PublishWorkflowRequest request = f.command.reserveSelection(f.intent); + assertThat(request.intent()).isEqualTo(f.intent); + assertThat(request.tenantId()).isEqualTo("private-tenant-key"); + assertThat(request.publishWorkflowId()) + .isEqualTo( + TemporalVersionPublishOrchestrator.workflowId( + f.intent.canonicalTenantId().toString(), f.intent.publishRequestId())); + verify(f.selections).reserve(f.intent); + verifyNoInteractions(f.versions, f.attempts, f.gate, f.exports); + } + + @Test + void newAttemptBindsExistingSelectedVersionAndDeniesBeforeUnreadyOwnerCarrier() { + Fixture f = new Fixture(); + PublishWorkflowRequest request = f.command.reserveSelection(f.intent); + Version version = new Version(); + version.setId(47L); + version.setTenantId(request.tenantId()); + version.setVersionNumber(6); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(9L); + when(f.versions.findByTenantIdAndIdForUpdate(request.tenantId(), 47L)) + .thenReturn(Optional.of(version)); + when(f.versions.findByTenantIdAndId(request.tenantId(), 47L)).thenReturn(Optional.of(version)); + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(request.tenantId()); + attempt.setVersionId(47L); + attempt.setVersionNumber(6); + attempt.setPublishWorkflowId(request.publishWorkflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setStatus(PublishAttemptStatus.PENDING); + attempt.setRequestDigest(f.selection.digest()); + when(f.attempts.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.empty(), Optional.empty(), Optional.of(attempt)); + + assertThatThrownBy(() -> f.command.reconcileFullVersionPublish(request)) + .hasMessageContaining("PUBLISH_OWNER_CARRIER_UNAVAILABLE"); + verify(f.attemptService) + .createFullVersionAttempt( + Mappers.getMapper(VersionMapper.class).toDto(version), + request.publishWorkflowId(), + f.selection.digest()); + verify(f.versions, never()).save(any()); + verify(f.versions, never()).findTopByTenantIdOrderByVersionNumberDesc(any()); + verifyNoInteractions(f.gate, f.exports); + } + + @Test + void changedNotesConflictBeforeAttemptOrContentWrites() { + Fixture f = new Fixture(); + PublishWorkflowRequest original = f.command.reserveSelection(f.intent); + PublishWorkflowRequest changed = + new PublishWorkflowRequest( + original.tenantId(), + "changed", + original.publishRequestId(), + original.publishWorkflowId(), + original.intent()); + assertThatThrownBy(() -> f.command.reconcileFullVersionPublish(changed)) + .hasMessageContaining("PUBLISH_ATTEMPT_IDENTITY_CONFLICT"); + verifyNoInteractions(f.versions, f.attempts, f.gate, f.exports); + } + + private static final class Fixture { + final PublishIntent intent = + new PublishIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "stable-request", + "9", + "original notes", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64)); + final AuthoredDraftPublishSelection selection = mock(AuthoredDraftPublishSelection.class); + final AuthoredDraftPublishSelectionRepository selections = + mock(AuthoredDraftPublishSelectionRepository.class); + final VersionRepository versions = mock(VersionRepository.class); + final PublishAttemptRepository attempts = mock(PublishAttemptRepository.class); + final PublishAttemptService attemptService = mock(PublishAttemptService.class); + final PublishGateService gate = mock(PublishGateService.class); + final AssetExportService exports = mock(AssetExportService.class); + final VersionPublishCommandServiceImpl command; + + Fixture() { + when(selection.intent()).thenReturn(intent); + when(selection.target()) + .thenReturn( + new TargetProof( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + 47L, + "private-tenant-key", + 8L, + "private-tenant-key", + "NEW_GAME_ROW")); + when(selection.digest()).thenReturn("sha256:" + "b".repeat(64)); + SelectionSnapshot snapshot = new SelectionSnapshot(selection, OffsetDateTime.now()); + when(selections.reserve(intent)).thenReturn(snapshot); + when(selections.readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId())) + .thenReturn(Optional.of(snapshot)); + when(attemptService.executeFullVersionTransaction(any())) + .thenAnswer(invocation -> ((Supplier) invocation.getArgument(0)).get()); + PublishedReleaseBundleService bundles = mock(PublishedReleaseBundleService.class); + when(bundles.findPublishedReleaseBundle(any(), any(Long.class))).thenReturn(Optional.empty()); + VersionAssetArtifactService artifacts = mock(VersionAssetArtifactService.class); + when(artifacts.findState(any(), any(Long.class))).thenReturn(Optional.empty()); + command = + new VersionPublishCommandServiceImpl( + versions, + mock(GameRepository.class), + attempts, + Mappers.getMapper(VersionMapper.class), + exports, + attemptService, + gate, + mock(ControlPlaneDigestService.class), + artifacts, + bundles, + mock(RecordedParticipantDigestService.class), + selections); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java index 5077165234..bc351186d0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java @@ -4,15 +4,33 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import org.junit.jupiter.api.Test; class TemporalVersionPublishActivitiesImplTest { @Test void pendingReconciliationIsReturnedAsNonterminalSnapshot() { VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + // Synthetic typed payload for Temporal status translation only; it is not owner authorization. + PublishIntent intent = + new PublishIntent( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "request-1", + "9", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); PublishWorkflowRequest request = new PublishWorkflowRequest( - "tenant-1", "notes", "request-1", "publish:tenant-1:publish-request:request-1"); + "private-tenant-key", + "notes", + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + intent); when(commandService.reconcileFullVersionPublish(request)) .thenThrow( new VersionPublishCommandServiceImpl.PendingReconciliationException( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java index 7d94da839a..abb2afb456 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java @@ -9,7 +9,16 @@ import org.junit.jupiter.api.Test; class TemporalVersionPublishOrchestratorTest { - private static final String WORKFLOW_ID = "publish:tenant-1:publish-request:request-1"; + private static final String WORKFLOW_ID = + "publish:11111111-1111-4111-8111-111111111111:publish-request:request-1"; + + @Test + void workflowIdentityUsesCanonicalTenantAndStableRequest() { + assertEquals( + WORKFLOW_ID, + TemporalVersionPublishOrchestrator.workflowId( + "11111111-1111-4111-8111-111111111111", "request-1")); + } @Test void timeoutPreservesPendingReconciliationCodeFromLastSnapshot() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index fb4dc917df..9d3e584d69 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -12,11 +12,24 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; @@ -71,6 +84,7 @@ class VersionPublishCommandServiceImplTest { @Mock private VersionAssetArtifactService versionAssetArtifactService; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private RecordedParticipantDigestService recordedParticipantDigestService; + @Mock private AuthoredDraftPublishSelectionRepository authoredSelections; private VersionPublishCommandServiceImpl service; @@ -110,11 +124,14 @@ void setup() { controlPlaneDigestService, versionAssetArtifactService, publishedReleaseBundleService, - recordedParticipantDigestService); + recordedParticipantDigestService, + authoredSelections); } @Test - void publishFullVersionUsesTenantScopedVersionSequence() { + void finalizeFullVersionUsesSelectedExistingDraftAndFiveMatchingParticipantCommits() { + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -147,17 +164,11 @@ void publishFullVersionUsesTenantScopedVersionSequence() { setCanonicalSource(savedPublished); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft, savedPublished); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(8); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.empty(), Optional.of(attempt)); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 8, selected.request(), selected.selection()); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn( Optional.of(savedDraft), @@ -167,14 +178,8 @@ void publishFullVersionUsesTenantScopedVersionSequence() { Optional.of(savedPublished)); ExportedAssetManifest exportedManifest = logoManifest(); - when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); List participantDigests = - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); + participantDigests(selected.selection(), 10L); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); when(versionAssetArtifactService.markExportedUnattested( @@ -191,7 +196,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { "EXPORTED_UNATTESTED", 3L, MANIFEST_HASH, - "workflow-1", + workflowId, null, null, LocalDateTime.now(), @@ -209,7 +214,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 10L, 8, "v1", - "publish:tenant-1:publish-request:workflow-1", + workflowId, MANIFEST_HASH, List.of("logo.png"), participantDigests, @@ -236,42 +241,42 @@ void publishFullVersionUsesTenantScopedVersionSequence() { "PUBLISHED", 4L, MANIFEST_HASH, - "workflow-1", + workflowId, null, null, LocalDateTime.now(), List.of("logo.png"))); - mockStagedExport(10L, 8, "publish:tenant-1:publish-request:workflow-1"); - - VersionDto dto = - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1"); + PublishWorkflowSnapshot snapshot = + service.finalizeFullVersion(selected.request(), participantDigests, exportedManifest); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); + assertEquals("SUCCEEDED", snapshot.status()); + assertEquals(10L, snapshot.versionId()); + assertEquals(VersionLifecycleState.PUBLISHED, savedDraft.getVersionState()); + assertEquals(2L, savedDraft.getVersionStateEpoch()); InOrder versionOrder = inOrder(versionRepository); versionOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); versionOrder.verify(versionRepository).save(any(Version.class)); - verify(publishAttemptService) + verify(versionRepository, never()).findTopByTenantIdOrderByVersionNumberDesc("tenant-1"); + verify(publishAttemptService, never()) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); - verify(assetExportService).exportAssets("tenant-1", 8); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(recordedParticipantDigestService) .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - InOrder publishOrder = inOrder(publishGateService, publishAttemptService, assetExportService); + InOrder publishOrder = inOrder(publishGateService, publishAttemptService); publishOrder .verify(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); - publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); publishOrder .verify(publishAttemptService) .recordFullVersionParticipantDigests(any(String.class), any(List.class)); } @Test - void publishFullVersionPropagatesTypedPublishGateFailures() { + void internalSelectedFinalizationPreservesTypedGateFailureBeforeWrites() { + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -288,52 +293,38 @@ void publishFullVersionPropagatesTypedPublishGateFailures() { savedDraft.setUpdatedAt(LocalDateTime.now()); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn( - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null))); + List digests = participantDigests(selected.selection(), 10L); org.mockito.Mockito.doThrow( new PublishGateFailureException( PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "recorded digest mismatch")) - .when(recordedParticipantDigestService) - .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); PublishGateFailureException thrown = assertThrows( PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + () -> service.finalizeFullVersion(selected.request(), digests, logoManifest())); assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); - verify(publishAttemptService) - .markFullVersionFailed( - any(String.class), - org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), - org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); + verify(publishAttemptService, never()) + .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any()); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { + void internalSelectedFinalizationRejectsOneParticipantOnAnotherCommitBeforeWrites() { + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -350,57 +341,54 @@ void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { savedDraft.setUpdatedAt(LocalDateTime.now()); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); List participantDigests = - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected")) - .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + new java.util.ArrayList<>(participantDigests(selected.selection(), 10L)); + PublishParticipantDigestDto worldDigest = participantDigests.get(1); + participantDigests.set( + 1, + new PublishParticipantDigestDto( + worldDigest.participantKey(), + worldDigest.scopeValue(), + worldDigest.baseVersionId(), + "99999999-9999-4999-8999-999999999999", + worldDigest.contentDigest(), + worldDigest.digestSchemaVersion(), + worldDigest.abilitySchemaDigest(), + worldDigest.errorCode(), + worldDigest.errorMessage())); PublishGateFailureException thrown = assertThrows( PublishGateFailureException.class, () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + service.finalizeFullVersion( + selected.request(), participantDigests, logoManifest())); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertEquals(PublishGateFailureCode.APPLIED_COMMIT_MISMATCH, thrown.failureCode()); + verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class)); verify(publishAttemptService, never()) .recordFullVersionParticipantDigests(any(String.class), any(List.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any()); } @Test - void publishFullVersionBundleWriteFailureLeavesAttemptPendingAndRetainsExportedAssets() { + void internalSelectedFinalizationBundleFailureLeavesAttemptPendingAndRetainsCandidate() { + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) - .thenReturn(Optional.empty()); Version savedDraft = new Version(); savedDraft.setId(10L); @@ -411,26 +399,16 @@ void publishFullVersionBundleWriteFailureLeavesAttemptPendingAndRetainsExportedA savedDraft.setUpdatedAt(LocalDateTime.now()); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); - when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(logoManifest()); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn( - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null))); + List digests = participantDigests(selected.selection(), 10L); + // The selected transaction seam receives an already-exported immutable candidate. + ExportedAssetManifest alreadyExportedCandidate = logoManifest(); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); when(versionAssetArtifactService.markExportedUnattested( @@ -447,7 +425,7 @@ void publishFullVersionBundleWriteFailureLeavesAttemptPendingAndRetainsExportedA "EXPORTED_UNATTESTED", 3L, MANIFEST_HASH, - "workflow-1", + workflowId, null, null, LocalDateTime.now(), @@ -461,13 +439,17 @@ void publishFullVersionBundleWriteFailureLeavesAttemptPendingAndRetainsExportedA any(String.class), any(List.class)); - mockStagedExport(10L, 1, "publish:tenant-1:publish-request:workflow-1"); assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + IllegalStateException.class, + () -> service.finalizeFullVersion(selected.request(), digests, alreadyExportedCandidate)); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(versionAssetArtifactService) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(assetExportService, never()) @@ -745,8 +727,11 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { @Test void readbackWithArtifactButNoBundleRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( @@ -771,9 +756,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileFullVersionPublish(selected.request())); assertTrue(thrown.getMessage().contains("incomplete")); verify(publishAttemptService, never()).executeFullVersionTransaction(any()); @@ -784,11 +767,15 @@ void readbackWithArtifactButNoBundleRemainsPartial() { } @Test - void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + void selectedPendingAttemptCanReadBackAnAlreadyCommittedTerminalRelease() { + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); - List participantDigests = participantDigests(); + List participantDigests = + participantDigests(selected.selection(), 10L); PublishedReleaseBundleDto bundle = new PublishedReleaseBundleDto( 1L, @@ -834,9 +821,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) .thenReturn(emptyManifest()); - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish(selected.request()); assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) @@ -857,23 +842,23 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { } @Test - void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { + void legacyPendingAttemptWithoutSelectionIsDeniedWithoutDigestBackfill() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); attempt.setId(101L); attempt.setRequestDigest(null); - Version mismatchedVersion = fullVersion(10L, 2, VersionLifecycleState.DRAFT); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(mismatchedVersion)); - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertTrue(thrown.getMessage().contains("PUBLISH_SELECTION_REQUIRED")); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(publishAttemptRepository, never()) .backfillFullVersionRequestDigestIfAbsent( any(Long.class), @@ -886,23 +871,24 @@ void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { } @Test - void legacyFullMixedScopeAttemptIsNotRebound() { + void legacyPendingMixedScopeAttemptIsDeniedWithoutSelectionBackfill() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); attempt.setId(101L); attempt.setRequestDigest(null); attempt.setBaseVersionId(3L); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertTrue(thrown.getMessage().contains("PUBLISH_SELECTION_REQUIRED")); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(publishAttemptRepository, never()) .backfillFullVersionRequestDigestIfAbsent( any(Long.class), @@ -916,17 +902,18 @@ void legacyFullMixedScopeAttemptIsNotRebound() { @Test void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); attempt.setScriptPatchVersion("legacy-patch"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(publishedReleaseBundleService, never()) @@ -1011,13 +998,17 @@ void mismatchedRequestDigestCannotReplaySucceededAttempt() { @Test void postBundleFailureAfterRollbackMarksFailureAndRetainsExportedAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - List participantDigests = participantDigests(); + List participantDigests = + participantDigests(selected.selection(), 10L); ExportedAssetManifest manifest = logoManifest(); PublishedReleaseBundleDto bundle = new PublishedReleaseBundleDto( @@ -1123,8 +1114,7 @@ void postBundleFailureAfterRollbackMarksFailureAndRetainsExportedAssets() { when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) .thenReturn(null, logoManifest(), logoManifest()); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + service.reconcileSelectedPublicationMechanics(selected.request()); assertEquals("FAILED", snapshot.status()); verify(publishAttemptService) @@ -1134,8 +1124,11 @@ void postBundleFailureAfterRollbackMarksFailureAndRetainsExportedAssets() { @Test void exactRetryResumesVerifiedStagedCandidateWithoutRestaging() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); VersionAssetArtifactStateDto stagedCandidate = stagedArtifact("tenant-1", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")); @@ -1148,15 +1141,13 @@ void exactRetryResumesVerifiedStagedCandidateWithoutRestaging() { .thenReturn(logoManifest()); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)) .thenThrow(new AssetExportOutcomePendingException("export readback is still pending")); assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); verify(versionAssetArtifactService, never()) .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); @@ -1168,8 +1159,11 @@ void exactRetryResumesVerifiedStagedCandidateWithoutRestaging() { @Test void participantGateFailureWithPriorStagedCandidateRemainsPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); @@ -1185,7 +1179,7 @@ void participantGateFailureWithPriorStagedCandidateRemainsPending() { .thenReturn(logoManifest()); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); org.mockito.Mockito.doThrow( new PublishGateFailureException( PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, @@ -1195,9 +1189,7 @@ void participantGateFailureWithPriorStagedCandidateRemainsPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); @@ -1210,8 +1202,11 @@ void participantGateFailureWithPriorStagedCandidateRemainsPending() { @MethodSource("invalidStagedRetryEvidence") void invalidStagedRetryEvidenceRemainsPendingWithoutExport( VersionAssetArtifactStateDto stagedArtifact, ExportedAssetManifest candidate) { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); @@ -1222,9 +1217,7 @@ void invalidStagedRetryEvidenceRemainsPendingWithoutExport( assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(publishAttemptService, never()) @@ -1233,7 +1226,7 @@ void invalidStagedRetryEvidenceRemainsPendingWithoutExport( } private static Stream invalidStagedRetryEvidence() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; + String workflowId = selectedWorkflowId("workflow-1"); return Stream.of( Arguments.of( stagedArtifact("tenant-2", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), @@ -1284,10 +1277,13 @@ private static VersionAssetArtifactStateDto stagedArtifact( @Test void changedArtifactDigestKeepsProofBearingPublicationPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); - List digests = participantDigests(); + List digests = participantDigests(selected.selection(), 10L); PublishedReleaseBundleDto bundle = new PublishedReleaseBundleDto( 1L, @@ -1334,9 +1330,7 @@ void changedArtifactDigestKeepsProofBearingPublicationPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileFullVersionPublish(selected.request())); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); @@ -1357,23 +1351,24 @@ void laterExporterConflictLeavesAttemptPendingForEarlierWriteReadback() { } private void assertExporterFailureLeavesPending(RuntimeException exportFailure) { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)).thenThrow(exportFailure); mockStagedExport(10L, 1, workflowId); assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(publishAttemptService, never()) @@ -1384,8 +1379,11 @@ private void assertExporterFailureLeavesPending(RuntimeException exportFailure) @Test void finalizationFailureWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); ExportedAssetManifest manifest = emptyManifest(); IllegalStateException operationFailure = @@ -1396,7 +1394,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()) @@ -1410,9 +1408,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); @@ -1431,8 +1427,11 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { value = Status.Code.class, names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); @@ -1444,9 +1443,7 @@ void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { IllegalStateException thrown = assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertTrue(thrown.getMessage().contains("temporarily unavailable")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); @@ -1458,8 +1455,11 @@ void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { @Test void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); ExportedAssetManifest manifest = emptyManifest(); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1467,7 +1467,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); @@ -1479,9 +1479,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { mockStagedExport(10L, 1, workflowId); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(publishAttemptService, never()) @@ -1493,8 +1491,11 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { @Test void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); ExportedAssetManifest manifest = emptyManifest(); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); @@ -1504,7 +1505,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()) @@ -1517,9 +1518,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); @@ -1535,8 +1534,11 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { @Test void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedRequest selected = selectedRequest("tenant-1", 10L, "notes", "workflow-1", "1"); + String workflowId = selected.request().publishWorkflowId(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); @@ -1547,7 +1549,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); + .thenReturn(participantDigests(selected.selection(), 10L)); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); @@ -1582,9 +1584,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> service.reconcileSelectedPublicationMechanics(selected.request())); assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); @@ -1610,6 +1610,173 @@ private PublishAttempt fullAttempt( return attempt; } + /** Creates explicit synthetic selected-commit facts for internal command-mechanics tests only. */ + private SelectedRequest selectedRequest( + String tenantId, + long versionId, + String notes, + String publishRequestId, + String expectedVersionStateEpoch) { + UUID canonicalTenantId = UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"); + UUID canonicalVersionId = UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); + UUID selectedCommitRequestId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID selectedCommitId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + TargetProof target = + new TargetProof( + canonicalTenantId, + canonicalVersionId, + versionId, + tenantId, + 1L, + tenantId, + "NEW_GAME_ROW"); + List revisions = + List.of( + new RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "synthetic internal publication fixture"), + new RevisionPayload( + "1", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "synthetic internal publication fixture"), + new RevisionPayload( + "2", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + Owner.ENTITY_MANAGEMENT, + "synthetic internal publication fixture"), + new RevisionPayload( + "3", + UUID.fromString("88888888-8888-4888-8888-888888888888"), + Owner.GAME_LOGIC, + "synthetic internal publication fixture"), + new RevisionPayload( + "4", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + Owner.AUTOMATION_SCRIPTING, + "synthetic internal publication fixture")); + List affectedUnits = + List.of( + new AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE, "fixture", "gd", "version", "1", "1"), + new AffectedUnit(Owner.WORLD_MANAGEMENT, "fixture", "world", "version", "1", "1"), + new AffectedUnit(Owner.ENTITY_MANAGEMENT, "fixture", "entity", "version", "1", "1"), + new AffectedUnit(Owner.GAME_LOGIC, "fixture", "logic", "version", "1", "1"), + new AffectedUnit( + Owner.AUTOMATION_SCRIPTING, "fixture", "automation", "version", "1", "1")); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + selectedCommitRequestId, + selectedCommitId, + "base-commit", + revisions, + affectedUnits); + PublishIntent intent = + new PublishIntent( + canonicalTenantId, + canonicalVersionId, + publishRequestId, + expectedVersionStateEpoch, + notes, + selectedCommitRequestId, + selectedCommitId, + binding.digest()); + String resultVectorJson = + "[" + + String.join( + ",", + java.util.Arrays.stream(Owner.values()) + .map( + owner -> + "{\"commitId\":\"" + + selectedCommitId + + "\",\"digest\":\"" + + binding.digest() + + "\",\"owner\":\"" + + owner.name() + + "\",\"status\":\"APPLIED\"}") + .toList()) + + "]"; + VisibilityFence fence = + new VisibilityFence( + target, + selectedCommitRequestId, + selectedCommitId, + binding.digest(), + resultVectorJson, + OffsetDateTime.now(ZoneOffset.UTC)); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + SelectionSnapshot snapshot = + new SelectionSnapshot(selection, OffsetDateTime.now(ZoneOffset.UTC)); + when(authoredSelections.reserve(intent)).thenReturn(snapshot); + when(authoredSelections.readByPublishRequest(canonicalTenantId, publishRequestId)) + .thenReturn(Optional.of(snapshot)); + PublishWorkflowRequest request = + new PublishWorkflowRequest( + tenantId, + notes, + publishRequestId, + TemporalVersionPublishOrchestrator.workflowId( + canonicalTenantId.toString(), publishRequestId), + intent); + return new SelectedRequest(selection, intent, snapshot, request); + } + + private static String selectedWorkflowId(String publishRequestId) { + return TemporalVersionPublishOrchestrator.workflowId( + "67d7b75b-42d1-4ac6-9572-684c5e633cda", publishRequestId); + } + + private PublishAttempt selectedAttempt( + PublishAttemptStatus status, + long versionId, + int versionNumber, + PublishWorkflowRequest request, + AuthoredDraftPublishSelection selection) { + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(request.tenantId()); + attempt.setVersionId(versionId); + attempt.setVersionNumber(versionNumber); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setPublishWorkflowId(request.publishWorkflowId()); + attempt.setStatus(status); + attempt.setRequestDigest(selection.digest()); + return attempt; + } + + private List participantDigests( + AuthoredDraftPublishSelection selection, long versionId) { + String commitId = selection.selectedCommit().commitId().toString(); + String scope = Long.toString(versionId); + return List.of( + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", + scope, + commitId, + "sha256:" + "1".repeat(64), + 1, + null, + null), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", scope, commitId, "sha256:" + "2".repeat(64), 1, null, null), + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", scope, commitId, "sha256:" + "3".repeat(64), 1, null, null), + new PublishParticipantDigestDto( + "GAME_LOGIC", scope, commitId, "sha256:" + "4".repeat(64), 1, null, null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", scope, commitId, "sha256:" + "5".repeat(64), 1, null, null)); + } + + private record SelectedRequest( + AuthoredDraftPublishSelection selection, + PublishIntent intent, + SelectionSnapshot snapshot, + PublishWorkflowRequest request) {} + private Version fullVersion(long versionId, int versionNumber, VersionLifecycleState state) { Version version = new Version(); version.setId(versionId); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index ab0f7786ac..4f6aabe1c3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.gamedesign.client.EntityManagementClient; import net.firedevops.firemud.gamedesign.client.GameLogicClient; import net.firedevops.firemud.gamedesign.client.WorldManagementClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -138,18 +139,6 @@ void setup() throws Exception { Optional.empty()); } - @Test - void publishVersionWithoutDurableWorkflowDoesNotMutate() { - IllegalStateException thrown = - assertThrows( - IllegalStateException.class, - () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); - - assertTrue(thrown.getMessage().startsWith("PUBLISH_WORKFLOW_UNAVAILABLE")); - verify(publishCommandService, org.mockito.Mockito.never()) - .publishFullVersion(any(), any(), any(), any()); - } - @Test void compareAndSetVersionStateLocksExactVersionBeforeSaving() { Version version = new Version(); @@ -1094,42 +1083,35 @@ private Version scriptPatchVersion( } @Test - void publishVersionPropagatesTypedPublishGateFailures() { - when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) - .thenThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")); - - PublishGateFailureException thrown = - org.junit.jupiter.api.Assertions.assertThrows( - PublishGateFailureException.class, - () -> serviceWithTemporal().publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); - - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); - } - - @Test - void publishVersionDeletesExportedAssetsWhenAttestationWriteFails() { - when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) - .thenReturn( - new VersionDto( - 10L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now())); + void publishVersionDeniesWithoutCurrentAccountAndOwnerEvidenceBeforeTemporalOrSideEffects() { + PublishIntent intent = + new PublishIntent( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + PUBLISH_REQUEST_ID, + "9", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); - VersionDto dto = serviceWithTemporal().publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> serviceWithTemporal().publishVersion(intent)); - assertEquals(10L, dto.id()); - verify(temporalPublishOrchestrator).publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE")); + org.mockito.Mockito.verifyNoInteractions( + temporalPublishOrchestrator, + publishCommandService, + publishAttemptService, + publishGateService, + assetExportService, + controlPlaneDigestService, + versionAssetArtifactService, + publishedReleaseBundleService, + recordedParticipantDigestService, + versionRepository, + gameRepository); } private VersionServiceImpl serviceWithTemporal() { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java new file mode 100644 index 0000000000..5b008b881a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import tools.jackson.databind.ObjectMapper; + +/** Immutable World-owned value and codec for the six version-scoped authored content families. */ +public final class WorldAuthoredGraph { + private static final int SNAPSHOT_SCHEMA_VERSION = 1; + + private final List> regions; + private final List> zones; + private final List> rooms; + private final List> roomExits; + private final List> generationRules; + private final List> spawnBindings; + + public WorldAuthoredGraph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + this.regions = copyRows(regions, false); + this.zones = copyRows(zones, false); + this.rooms = copyRows(rooms, false); + this.roomExits = copyRows(roomExits, false); + this.generationRules = copyRows(generationRules, false); + this.spawnBindings = copyRows(spawnBindings, false); + } + + public List> regions() { + return copyRows(regions, true); + } + + public List> zones() { + return copyRows(zones, true); + } + + public List> rooms() { + return copyRows(rooms, true); + } + + public List> roomExits() { + return copyRows(roomExits, true); + } + + public List> generationRules() { + return copyRows(generationRules, true); + } + + public List> spawnBindings() { + return copyRows(spawnBindings, true); + } + + /** + * Encodes the canonical snapshot representation using the capture component's configured mapper. + */ + public byte[] encode(ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + LinkedHashMap root = new LinkedHashMap<>(); + root.put("snapshotSchemaVersion", SNAPSHOT_SCHEMA_VERSION); + root.put("regions", regions); + root.put("zones", zones); + root.put("rooms", rooms); + root.put("roomExits", roomExits); + root.put("generationRules", generationRules); + root.put("worldEntitySpawnBindings", spawnBindings); + try { + return objectMapper.writeValueAsBytes(root); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + WorldAuthoredGraph withRegions(List> updatedRegions) { + return new WorldAuthoredGraph( + updatedRegions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private static List> copyRows( + List> rows, boolean immutable) { + Objects.requireNonNull(rows, "rows"); + List> copiedRows = new ArrayList<>(rows.size()); + for (Map row : rows) { + Objects.requireNonNull(row, "row"); + LinkedHashMap copiedRow = new LinkedHashMap<>(); + for (Map.Entry entry : row.entrySet()) { + copiedRow.put( + Objects.requireNonNull(entry.getKey(), "row key"), + copyValue(entry.getValue(), immutable)); + } + copiedRows.add(immutable ? Collections.unmodifiableMap(copiedRow) : copiedRow); + } + return immutable ? Collections.unmodifiableList(copiedRows) : copiedRows; + } + + private static Object copyValue(Object value, boolean immutable) { + if (value == null + || value instanceof String + || value instanceof Byte + || value instanceof Short + || value instanceof Integer + || value instanceof Long + || value instanceof Float + || value instanceof Double + || value instanceof BigInteger + || value instanceof BigDecimal + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum) { + return value; + } + if (value instanceof byte[] bytes) { + return bytes.clone(); + } + if (value instanceof Map map) { + LinkedHashMap copiedMap = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw new IllegalArgumentException("Authored graph object keys must be strings"); + } + copiedMap.put(key, copyValue(entry.getValue(), immutable)); + } + return immutable ? Collections.unmodifiableMap(copiedMap) : copiedMap; + } + if (value instanceof List list) { + List copiedList = new ArrayList<>(list.size()); + for (Object item : list) { + copiedList.add(copyValue(item, immutable)); + } + return immutable ? Collections.unmodifiableList(copiedList) : copiedList; + } + throw new IllegalArgumentException( + "Unsupported mutable value in authored graph: " + value.getClass().getName()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java index ca8bbea36a..e253237762 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -36,7 +36,6 @@ * publication eligibility or proof that World applied a complete synchronized owner commit. */ public class WorldAuthoredGraphSnapshotCapture { - private static final int GRAPH_SCHEMA_VERSION = 1; private static final int WORLD_DIGEST_SCHEMA_VERSION = 2; private static final Table REGION = table("region"); @@ -141,8 +140,8 @@ public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { } String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); - Graph graph = readAndValidateGraph(provenance); - byte[] graphBytes = encodeGraph(graph); + WorldAuthoredGraph graph = readAndValidateGraph(provenance); + byte[] graphBytes = graph.encode(objectMapper); WorldDraftDesignDigest currentDigest = draftDigestService.getDraftDesignDigest( Long.toString(provenance.localTenantKey()), @@ -236,7 +235,7 @@ private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvena return writeJson(evidence); } - private Graph readAndValidateGraph(OwnerProvenance provenance) { + private WorldAuthoredGraph readAndValidateGraph(OwnerProvenance provenance) { long tenantKey = provenance.localTenantKey(); long versionKey = provenance.localVersionKey(); List regionRows = fetch(REGION, tenantKey, versionKey); @@ -427,7 +426,7 @@ private Graph readAndValidateGraph(OwnerProvenance provenance) { item.put("respawnDelaySeconds", delay); bindings.add(item); } - return new Graph(regions, zones, rooms, exits, rules, bindings); + return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); } private List fetch(Table table, long tenantKey, long versionKey) { @@ -469,18 +468,6 @@ private long parseCanonicalPositiveId(String value, String label, long rowId) { } } - private byte[] encodeGraph(Graph graph) { - LinkedHashMap root = new LinkedHashMap<>(); - root.put("snapshotSchemaVersion", GRAPH_SCHEMA_VERSION); - root.put("regions", graph.regions()); - root.put("zones", graph.zones()); - root.put("rooms", graph.rooms()); - root.put("roomExits", graph.roomExits()); - root.put("generationRules", graph.generationRules()); - root.put("worldEntitySpawnBindings", graph.spawnBindings()); - return writeJsonBytes(root); - } - private String encodeTuples(List tuples) { List> values = new ArrayList<>(); for (OwnedAffectedTuple tuple : tuples) { @@ -613,12 +600,4 @@ static String sha256(byte[] bytes) { throw new IllegalStateException("SHA-256 unavailable", exception); } } - - private record Graph( - List> regions, - List> zones, - List> rooms, - List> roomExits, - List> generationRules, - List> spawnBindings) {} } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java new file mode 100644 index 0000000000..fd8273bbe5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan.RegionRevision; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; + +/** Pure staging transform for an already supplied and validated World REGION commit plan. */ +public final class WorldDraftRegionGraphStager { + private static final Set CAPTURED_REGION_FIELDS = + Set.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + + /** + * Immutable in-memory content only; this is not APPLIED proof, commit authorization, synchronized + * Draft visibility, or release-eligible content. + */ + public record UnverifiedStagedContent( + DraftCommitBinding binding, OwnerBinding ownerBinding, WorldAuthoredGraph graph) { + public UnverifiedStagedContent { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + Objects.requireNonNull(graph, "graph"); + } + } + + /** Applies all supported plan revisions to a copy of the supplied graph or returns no result. */ + public UnverifiedStagedContent stage( + WorldDraftRegionCommitPlan plan, WorldAuthoredGraph priorGraph) { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(priorGraph, "priorGraph"); + + List> regions = new ArrayList<>(priorGraph.regions()); + Map regionIndexes = indexRegions(regions); + Set updatedRegionIds = new HashSet<>(); + + for (RegionRevision revision : plan.regionRevisions()) { + WorldDesignMutationRevision mutation = revision.mutation(); + long regionId = parseRegionId(mutation.getAggregateId()); + if (!updatedRegionIds.add(regionId)) { + throw invalid("World region plan contains a duplicate staging target"); + } + Integer index = regionIndexes.get(regionId); + if (index == null) { + throw invalid("World region staging target does not exist in the supplied graph"); + } + + Map priorRegion = regions.get(index); + validateExistingRegion(priorRegion, regionId); + RegionDesignMutation payload = mutation.getRegion(); + validatePayload(payload); + LinkedHashMap updatedRegion = new LinkedHashMap<>(priorRegion); + updatedRegion.put("shardId", payload.getShardId()); + updatedRegion.put("name", payload.getName()); + updatedRegion.put("weather", blankToNull(payload.getWeather())); + updatedRegion.put("generationSeed", payload.getGenerationSeed()); + updatedRegion.put("generatorType", blankToNull(payload.getGeneratorType())); + updatedRegion.put("generatorParams", blankToNull(payload.getGeneratorParams())); + updatedRegion.put( + "spacingMultiplier", + payload.getSpacingMultiplier() == 0.0d ? 1.0d : payload.getSpacingMultiplier()); + regions.set(index, updatedRegion); + } + + WorldAuthoredGraph stagedGraph = priorGraph.withRegions(regions); + return new UnverifiedStagedContent(plan.binding(), plan.ownerBinding(), stagedGraph); + } + + private static Map indexRegions(List> regions) { + Map indexes = new HashMap<>(); + for (int index = 0; index < regions.size(); index++) { + Object rawId = regions.get(index).get("id"); + if (!(rawId instanceof Long id) || id <= 0L) { + throw invalid("Supplied World graph contains a missing or inconsistent region ID"); + } + if (indexes.putIfAbsent(id, index) != null) { + throw invalid("Supplied World graph contains duplicate region IDs"); + } + } + return indexes; + } + + private static void validateExistingRegion(Map region, long expectedId) { + if (!region.keySet().equals(CAPTURED_REGION_FIELDS) + || !Objects.equals(region.get("id"), expectedId) + || !(region.get("shardId") instanceof Integer shardId) + || shardId < 0 + || !(region.get("name") instanceof String name) + || name.isBlank() + || !nullableString(region.get("weather")) + || !(region.get("generationSeed") instanceof Long) + || !nullableString(region.get("generatorType")) + || !nullableString(region.get("generatorParams")) + || !(region.get("spacingMultiplier") instanceof Double spacingMultiplier) + || !Double.isFinite(spacingMultiplier) + || spacingMultiplier <= 0.0d) { + throw invalid("Supplied World graph contains an inconsistent existing region target"); + } + } + + private static void validatePayload(RegionDesignMutation payload) { + if (payload.getName().isBlank()) { + throw invalid("World region staging requires a nonempty region name"); + } + if (payload.getShardId() < 0) { + throw invalid("World region staging does not support a negative shard ID"); + } + double spacingMultiplier = payload.getSpacingMultiplier(); + if (!Double.isFinite(spacingMultiplier) || spacingMultiplier < 0.0d) { + throw invalid("World region staging requires finite nonnegative spacing"); + } + } + + private static long parseRegionId(String value) { + try { + long id = Long.parseLong(value); + if (id <= 0L || !Long.toString(id).equals(value)) { + throw new NumberFormatException("not a canonical positive region ID"); + } + return id; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("World region staging target ID is invalid", exception); + } + } + + private static boolean nullableString(Object value) { + return value == null || value instanceof String; + } + + private static String blankToNull(String value) { + return value.isBlank() ? null : value; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java index 369aa953bc..02801037d3 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -262,11 +262,14 @@ void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { WorldAuthoredVersionIdentityReceipt firstIdentity = identity(first, GAME_DESIGN_VERSION_A); long secondGameDesignVersionId = firstIdentity.localVersionKey(); WorldAuthoredSourceIntakeReceipt second = - intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_102L); + intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_101L); WorldAuthoredVersionIdentityReceipt secondIdentity = identity(second, secondGameDesignVersionId); assertThat(secondGameDesignVersionId).isEqualTo(firstIdentity.localVersionKey()); assertThat(secondIdentity.localVersionKey()).isNotEqualTo(secondGameDesignVersionId); + assertThatThrownBy(() -> intake(canonicalTenantId, "contradictory-world", tenantSlug, 8_103L)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class) + .hasMessageContaining("Canonical tenant source or stable tenant selector conflicts"); WorldDesignPublicationFenceEvidence firstRequest = evidence(first, "shared-publication-request", GAME_DESIGN_VERSION_A, 5L); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java new file mode 100644 index 0000000000..d9c3a198dd --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java @@ -0,0 +1,140 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraph; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class WorldAuthoredGraphTest { + + @Test + void encodesTheExistingSixFamilySnapshotShapeAndFieldOrder() { + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + List.of( + row( + "id", + 9_000_000_042L, + "shardId", + 3, + "name", + "Northern Reach", + "weather", + null, + "generationSeed", + Long.MIN_VALUE, + "generatorType", + null, + "generatorParams", + null, + "spacingMultiplier", + 1.0d)), + List.of( + row("id", 900_000_000_000_000_042L, "regionId", 9_000_000_042L, "name", "North")), + List.of( + row( + "id", + 8_000_000_000_000_000_042L, + "zoneId", + 900_000_000_000_000_042L, + "name", + "Keep", + "description", + null, + "nameLocalizedVariantsJson", + null, + "descriptionLocalizedVariantsJson", + "{\"en\":\"Keep\"}")), + List.of( + row( + "id", 7_000_000_000_000_000_042L, + "fromRoomId", 8_000_000_000_000_000_042L, + "toRoomId", 8_000_000_000_000_000_043L, + "direction", "north", + "cost", 2)), + List.of( + row( + "id", 6_000_000_000_000_000_042L, + "name", "weather-profile", + "scopeType", "REGION_SUBTREE", + "scopeId", "9", + "value", "{\"rain\":true}")), + List.of( + row( + "id", + 5_000_000_000_000_000_042L, + "roomId", + 8_000_000_000_000_000_042L, + "entityTemplateType", + "NPC", + "entityTemplateId", + 9_000_000_000_000_000_042L, + "spawnCount", + 4, + "respawnDelaySeconds", + 30))); + + assertThat(new String(graph.encode(new ObjectMapper()), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"snapshotSchemaVersion\":1,\"regions\":[{\"id\":9000000042,\"shardId\":3," + + "\"name\":\"Northern Reach\",\"weather\":null,\"generationSeed\":-9223372036854775808," + + "\"generatorType\":null,\"generatorParams\":null,\"spacingMultiplier\":1.0}]," + + "\"zones\":[{\"id\":900000000000000042,\"regionId\":9000000042,\"name\":\"North\"}]," + + "\"rooms\":[{\"id\":8000000000000000042,\"zoneId\":900000000000000042," + + "\"name\":\"Keep\",\"description\":null,\"nameLocalizedVariantsJson\":null," + + "\"descriptionLocalizedVariantsJson\":\"{\\\"en\\\":\\\"Keep\\\"}\"}]," + + "\"roomExits\":[{\"id\":7000000000000000042,\"fromRoomId\":8000000000000000042," + + "\"toRoomId\":8000000000000000043,\"direction\":\"north\",\"cost\":2}]," + + "\"generationRules\":[{\"id\":6000000000000000042,\"name\":\"weather-profile\"," + + "\"scopeType\":\"REGION_SUBTREE\",\"scopeId\":\"9\"," + + "\"value\":\"{\\\"rain\\\":true}\"}]," + + "\"worldEntitySpawnBindings\":[{\"id\":5000000000000000042," + + "\"roomId\":8000000000000000042,\"entityTemplateType\":\"NPC\"," + + "\"entityTemplateId\":9000000000000000042,\"spawnCount\":4," + + "\"respawnDelaySeconds\":30}]}"); + } + + @Test + void deeplyCopiesNestedRowsCollectionsAndByteArrays() { + byte[] suppliedBytes = {1, 2, 3}; + List suppliedItems = new ArrayList<>(List.of("before", suppliedBytes)); + Map suppliedNested = new LinkedHashMap<>(); + suppliedNested.put("items", suppliedItems); + Map suppliedRow = new LinkedHashMap<>(); + suppliedRow.put("id", 7L); + suppliedRow.put("extension", suppliedNested); + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + List.of(), List.of(suppliedRow), List.of(), List.of(), List.of(), List.of()); + + suppliedItems.set(0, "after"); + suppliedBytes[0] = 9; + Map nested = (Map) graph.zones().getFirst().get("extension"); + List items = (List) nested.get("items"); + byte[] exposedBytes = (byte[]) items.get(1); + exposedBytes[0] = 8; + + assertThat(items.getFirst()).isEqualTo("before"); + Map freshNested = (Map) graph.zones().getFirst().get("extension"); + List freshItems = (List) freshNested.get("items"); + assertThat((byte[]) freshItems.get(1)).containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThatThrownBy(() -> graph.zones().getFirst().put("newField", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(items::clear).isInstanceOf(UnsupportedOperationException.class); + } + + private static LinkedHashMap row(Object... values) { + LinkedHashMap row = new LinkedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + row.put((String) values[index], values[index + 1]); + } + return row; + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java new file mode 100644 index 0000000000..697b29635b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java @@ -0,0 +1,366 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraph; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionGraphStagerTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String PREFIXED_DIGEST = "sha256:" + "a".repeat(64); + private static final long LARGE_REGION_ID = 9_223_372_036_854_775_806L; + + @Test + void stagesOrderedExistingRegionsAndPreservesBindingRowsAndUntouchedFamilies() { + RegionSpec first = + new RegionSpec( + LARGE_REGION_ID, + uuid(5), + RegionDesignMutation.newBuilder() + .setName("Updated North") + .setWeather("rain") + .setShardId(3) + .setGenerationSeed(Long.MAX_VALUE) + .setGeneratorType("cave") + .setGeneratorParams("density=4") + .setSpacingMultiplier(0.0d) + .build(), + Long.MAX_VALUE - 1L, + Long.MAX_VALUE - 2L); + RegionSpec second = + new RegionSpec( + 19L, + uuid(6), + RegionDesignMutation.newBuilder() + .setName("Updated South") + .setWeather(" ") + .setShardId(0) + .setGenerationSeed(Long.MIN_VALUE) + .setGeneratorType(" ") + .setGeneratorParams("\t") + .setSpacingMultiplier(2.5d) + .build(), + 7, + 9); + WorldDraftRegionCommitPlan plan = plan(first, second); + WorldAuthoredGraph priorGraph = + graph( + List.of( + region(99L, "Untouched", "clear", "old", "old params", 10L, 1.5d), + region(LARGE_REGION_ID, "Old North", "snow", "old", "old params", 11L, 0.75d), + region(19L, "Old South", "sun", "old", "old params", 12L, 3.0d)), + List.of(row(101L)), + List.of(row(201L)), + List.of(row(301L)), + List.of(row(401L)), + List.of(row(501L))); + + WorldDraftRegionGraphStager.UnverifiedStagedContent staged = + new WorldDraftRegionGraphStager().stage(plan, priorGraph); + + assertThat(staged.binding()).isSameAs(plan.binding()); + assertThat(staged.ownerBinding()).isSameAs(plan.ownerBinding()); + assertThat(staged.binding().baseCommitId()) + .isEqualTo("base-commit-from-an-older-disjoint-snapshot"); + assertThat(staged.binding().affectedUnits(Owner.WORLD_MANAGEMENT)) + .extracting(AffectedUnit::expectedEpoch) + .contains("9223372036854775806", "9223372036854775805"); + assertThat(plan.regionRevisions()) + .extracting(revision -> revision.revisionOrder()) + .containsExactly("0", "2"); + assertThat(staged.graph().regions()) + .extracting(row -> row.get("id")) + .containsExactly(99L, LARGE_REGION_ID, 19L); + assertThat(staged.graph().regions().get(0)).containsEntry("name", "Untouched"); + assertThat(staged.graph().regions().get(1)) + .containsEntry("id", LARGE_REGION_ID) + .containsEntry("shardId", 3) + .containsEntry("name", "Updated North") + .containsEntry("weather", "rain") + .containsEntry("generationSeed", Long.MAX_VALUE) + .containsEntry("generatorType", "cave") + .containsEntry("generatorParams", "density=4") + .containsEntry("spacingMultiplier", 1.0d); + assertThat(staged.graph().regions().get(2)) + .containsEntry("id", 19L) + .containsEntry("name", "Updated South") + .containsEntry("weather", null) + .containsEntry("generationSeed", Long.MIN_VALUE) + .containsEntry("generatorType", null) + .containsEntry("generatorParams", null) + .containsEntry("spacingMultiplier", 2.5d); + assertThat(staged.graph().zones()).containsExactlyElementsOf(priorGraph.zones()); + assertThat(staged.graph().rooms()).containsExactlyElementsOf(priorGraph.rooms()); + assertThat(staged.graph().roomExits()).containsExactlyElementsOf(priorGraph.roomExits()); + assertThat(staged.graph().generationRules()) + .containsExactlyElementsOf(priorGraph.generationRules()); + assertThat(staged.graph().spawnBindings()) + .containsExactlyElementsOf(priorGraph.spawnBindings()); + assertThat(priorGraph.regions().get(1)).containsEntry("name", "Old North"); + } + + @Test + void rejectsUnsupportedMissingDuplicateInconsistentAndInvalidTargetsWithoutPartialOutput() { + RegionSpec first = validSpec(LARGE_REGION_ID, uuid(5)); + RegionSpec missing = validSpec(19L, uuid(6)); + WorldDraftRegionCommitPlan twoRegionPlan = plan(first, missing); + WorldAuthoredGraph missingSecondTarget = + graph(List.of(region(LARGE_REGION_ID, "Old North", null, null, null, 12L, 1.0d))); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDraftRegionGraphStager().stage(twoRegionPlan, missingSecondTarget)); + assertThat(missingSecondTarget.regions()).hasSize(1); + assertThat(missingSecondTarget.regions().getFirst()).containsEntry("name", "Old North"); + + WorldDraftRegionCommitPlan oneRegionPlan = plan(first); + WorldAuthoredGraph duplicateTargets = + graph( + List.of( + region(LARGE_REGION_ID, "North A", null, null, null, 1L, 1.0d), + region(LARGE_REGION_ID, "North B", null, null, null, 2L, 1.0d))); + assertThatIllegalArgumentException() + .isThrownBy(() -> new WorldDraftRegionGraphStager().stage(oneRegionPlan, duplicateTargets)); + + Map inconsistentRegion = + region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + inconsistentRegion.put("id", (int) LARGE_REGION_ID); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage(oneRegionPlan, graph(List.of(inconsistentRegion)))); + + Map missingField = region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + missingField.remove("weather"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage(oneRegionPlan, graph(List.of(missingField)))); + + Map extraField = region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + extraField.put("unrecognized", "value"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager().stage(oneRegionPlan, graph(List.of(extraField)))); + + RegionSpec negativeShard = + new RegionSpec( + LARGE_REGION_ID, + uuid(7), + RegionDesignMutation.newBuilder().setName("Bad shard").setShardId(-1).build(), + 1, + 1); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage( + plan(negativeShard), + graph( + List.of( + region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d))))); + + RegionSpec nonfiniteSpacing = + new RegionSpec( + LARGE_REGION_ID, + uuid(8), + RegionDesignMutation.newBuilder() + .setName("Bad spacing") + .setSpacingMultiplier(Double.NaN) + .build(), + 1, + 1); + assertThatIllegalArgumentException().isThrownBy(() -> plan(nonfiniteSpacing)); + + WorldDesignMutationRevision unsupportedMutation = + mutation(first, WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE); + assertThatIllegalArgumentException() + .isThrownBy(() -> planWithMutations(List.of(unsupportedMutation), List.of(first))); + } + + private static WorldDraftRegionCommitPlan plan(RegionSpec... specs) { + List mutations = new ArrayList<>(); + for (RegionSpec spec : specs) { + mutations.add( + mutation(spec, WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT)); + } + return planWithMutations(mutations, List.of(specs)); + } + + private static WorldDraftRegionCommitPlan planWithMutations( + List worldMutations, List specs) { + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + int revisionOrder = 0; + for (int index = 0; index < worldMutations.size(); index++) { + WorldDesignMutationRevision mutation = worldMutations.get(index); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisionOrder++), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(mutation))); + RegionSpec spec = specs.get(index); + units.add(worldUnit(Long.toString(spec.regionId()), "AGGREGATE", spec.aggregateEpoch())); + units.add(worldUnit(Long.toString(spec.regionId()), "REGION_SUBTREE", spec.scopeEpoch())); + if (index == 0) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisionOrder++), + uuid(30), + Owner.GAME_LOGIC, + "opaque game logic revision")); + units.add( + new AffectedUnit( + Owner.GAME_LOGIC, "ABILITY", "ability-17", "AGGREGATE", "ability-17", "2")); + } + } + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT_ID, + VERSION_ID, + GAME_DESIGN_VERSION_ID, + "tenant-123", + 1001L, + "tenant-123", + "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-commit-from-an-older-disjoint-snapshot", + revisions, + units); + return WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + } + + private static WorldDesignMutationRevision mutation( + RegionSpec spec, WorldDesignMutationOperation operation) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(spec.revisionId().toString()) + .setCommitId(COMMIT_ID.toString()) + .setOperation(operation) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(Long.toString(spec.regionId())) + .setExpectedDraftRevisionEpoch(spec.aggregateEpoch()) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(spec.regionId())) + .setExpectedDraftScopeRevisionEpoch(spec.scopeEpoch()) + .setRegion(spec.payload()) + .build(); + } + + private static RegionSpec validSpec(long id, UUID revisionId) { + return new RegionSpec( + id, + revisionId, + RegionDesignMutation.newBuilder().setName("Updated").setSpacingMultiplier(1.0d).build(), + 1, + 1); + } + + private static WorldAuthoredGraph graph(List> regions) { + return graph(regions, List.of(), List.of(), List.of(), List.of(), List.of()); + } + + private static WorldAuthoredGraph graph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + return new WorldAuthoredGraph(regions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private static Map region( + long id, + String name, + String weather, + String generatorType, + String generatorParams, + long generationSeed, + double spacingMultiplier) { + LinkedHashMap row = new LinkedHashMap<>(); + row.put("id", id); + row.put("shardId", 0); + row.put("name", name); + row.put("weather", weather); + row.put("generationSeed", generationSeed); + row.put("generatorType", generatorType); + row.put("generatorParams", generatorParams); + row.put("spacingMultiplier", spacingMultiplier); + return row; + } + + private static Map row(long id) { + LinkedHashMap row = new LinkedHashMap<>(); + row.put("id", id); + return row; + } + + private static AffectedUnit worldUnit(String id, String scopeType, long epoch) { + return new AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", id, scopeType, id, Long.toString(epoch)); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + "firemud", + TENANT_ID, + VERSION_ID, + uuid(40), + GAME_DESIGN_VERSION_ID, + uuid(41), + uuid(42), + PREFIXED_DIGEST, + uuid(43), + PREFIXED_DIGEST, + PREFIXED_DIGEST); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "Test World revision could not be rendered as JSON", exception); + } + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", value, value)); + } + + private record RegionSpec( + long regionId, + UUID revisionId, + RegionDesignMutation payload, + long aggregateEpoch, + long scopeEpoch) {} +} From 9cf395d17398fe0b7fef8fae3a9e58d59e2ed949 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:35:25 +1300 Subject: [PATCH 03/11] Order retained role changes behind exact Draft outcomes and repair publication proof --- .github/workflows/ci.yml | 11 + ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 + .../world-runtime-and-movement.md | 2 + .../DraftAuthorizationFenceBinding.java | 79 ++++ .../DraftAuthorizationFenceRepository.java | 31 ++ .../AccountTenantRoleOperationRepository.java | 67 ++- .../AccountTenantRoleMutationService.java | 156 ++++++- ...nant_role_pending_draft_source_changes.sql | 162 +++++++ .../AccountJoinPostgresIntegrationTest.java | 422 ++++++++++++++++++ ...tionRepositoryPostgresIntegrationTest.java | 147 +++++- .../DraftAuthorizationFenceBindingTest.java | 42 ++ ...lected_publish_attempt_digest_capacity.sql | 5 + ...ishSelectionRepositoryIntegrationTest.java | 67 +++ .../tenant/WorldAuthoredGraph.java | 326 ++++++++++++++ .../tenant/WorldAuthoredGraphReader.java | 325 ++++++++++++++ .../WorldAuthoredGraphSnapshotCapture.java | 286 +----------- ...WorldDesignPublicationFenceRepository.java | 14 + .../WorldDraftRegionStagingService.java | 65 +++ ...dGraphSnapshotPostgresIntegrationTest.java | 348 ++++++++++++++- .../tenant/WorldAuthoredGraphTest.java | 191 +++++++- .../WorldDraftRegionStagingServiceTest.java | 142 ++++++ 22 files changed, 2572 insertions(+), 320 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V58__tenant_role_pending_draft_source_changes.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c236db859f..b8a42d51f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2151,6 +2151,7 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#samePublicationRequestCannotSelectAnotherVersionInTheSameTenant()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#concurrentPublicationRequestClaimsAcrossVersionsRetainOnlyOneSelection()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#v44PreservesExactSelectionsRetainedAtV43()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#v45PreservesRetainedAttemptDigestsAndStoresExactSelectionDigest()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#v44RejectsConflictingRetainedRequestAcrossVersionsWithoutDiscardingEitherHistory()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepositoryIntegrationTest#versionRowLockSerializesSelectionAgainstApplicationSlotClaim()' \ game-design-service @@ -2166,6 +2167,10 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#wrongTenantVersionParentEdgeDeniesCaptureBeforeSnapshotRetention()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedOpenStagingReadsAllSixFamiliesWithoutChangingDatabaseContent()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsChangedIntakeEvidenceBeforeOwnerCreation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsFrozenOwnerBeforeReadingAnInvalidPriorGraph()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsCrossVersionParentAndLateInvalidRevisionWithoutAnyApply()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#rollbackAndCommittedExactReadbackRetainOneImmutableAttempt()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes()' \ @@ -2206,7 +2211,13 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSource()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#invalidatingTenantRoleMutationDeniesFenceOverflowWithoutChangingAnyAccountSource()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentOpposingTenantAdminTransfersLeaveOneCurrentAdministrator()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleSourceWaitsForBothCommittedOwnersAndRecoversOriginalPendingCapture()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleRevocationWinsOrderButWaitsForBothFencedAbortReadbacks()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleTransferParticipatesInBothMembershipsAndAccountIssuanceScope()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRolePendingRetryRejectsChangedIdentityAndNeverRecapturesLaterSource()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#immutableJournalRetriesOriginalBytesAfterLaterRoleOperationAndRejectsChangedIntent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#forwardPendingMigrationPreservesExistingV56CommittedResultExactly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#onlyExactLinkedWaitingIntentMayPersistAndItsCaptureCannotBeChanged()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#operationJournalAndMemberEvidenceRollBackTogether()' \ account-service diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index cfe6cd069a..f55cf123b2 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The selected-Draft candidate now includes V45, a lossless widening of `publish_attempt.request_digest` from 64 to 71 characters for the exact prefixed selection digest. A V44-to-V45 case retains pending, successful and failed attempts, including absent historical digests, then writes and independently reads an exact selected digest. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) executed all five publication transaction tests: three passed, but the two selected-Draft cases failed because the production attempt column could not store that digest. The same run executed 14 descriptor mTLS and eight descriptor PostgreSQL cases successfully; the nine coordinator and eight selection cases were not run after the earlier failure and have no raw proof. Corrected PostgreSQL execution remains required. V24 already provides workflow-ID capacity and is not changed. These internal mechanics do not enable public publication or supply missing authenticated owner/release producers. + The authored-publication candidate adds an internal durable Draft coordinator and exact existing-Draft selection. The shared complete-input codec retains the canonical target, exact base, ordered full revisions and complete declared owner/aggregate/scope epochs. V42 retains immutable owner results, definitive final abort and synchronized visibility; a definitive mixed vector becomes failed nonpublication without rewriting outcomes or advancing the prior view. V43 retains the first selected synchronized commit; V44 additionally enforces one Version per canonical tenant/publication-request identity without discarding conflicting retained history. The request, Temporal envelope and attempt carry the complete original selection and use the server-resolved existing Version, not a newly allocated empty Version. Public publication denies before dispatch or mutation while the current Account actor/role/party/terms producer and authenticated owner freeze/materialization are missing. Internal selected pending execution also denies before incompatible legacy participant calls or export. Historical provable terminal readback remains separate and does not manufacture missing selection evidence. These components do not prove normal synchronized editor reads, authenticated owner commits or complete release publication. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) owns that contract. The earlier consolidated four-module gate passed with 1,931 clean unit results and one MinIO skip, while all 545 PostgreSQL nodes skipped locally without Docker. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for `c5fd96e935028b72182d58a611152bee6a8e533b`, records nine coordinator methods executing with four passes and five failures; all four selection methods failed. The failures exposed `updated_at` bound as text to PostgreSQL `timestamptz`, not skipped tests or flaky outcomes. The three affected SQL sites now cast that parameter explicitly. The corrected selection/staging candidate passes combined Game Design/World full checks, both boot JARs, formatting, Checkstyle, SpotBugs, links and Markdown: 515 Game Design and 246 World unit cases pass, one MinIO case skips, and all 189 PostgreSQL methods skip without Docker. V44 jOOQ generation, Flyway sanity, 230 architecture contracts and workflow/tooling checks pass. The cross-Version request race, exact V43-to-V44 retained-row equality and conflicting-history migration cases compile but have not executed; CI strictly requires all 38 named coordination/selection/graph/fence methods. Five existing PostgreSQL publication-transaction methods retain their rollback, exact readback, immutable release and remap-retention obligations, using explicitly synthetic selection prerequisites for internal mechanics rather than authenticated publication. Account's nine fence cases executed cleanly at the earlier head; World has a separate cross-Version fixture correction and missing graph execution proof. Corrected database execution remains open; no green composed or activation claim follows. Complete Account source-writer/currentness proof, canonical selected-commit participant carriers, synchronized visibility, released-graph readback and lifecycle materialization remain required. 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 8fc674cf20..78943b17e7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The current authored-publication candidate connects the explicitly unwired retained `EXPLICIT_JOIN` tenant-role writer to V57 source-change ordering. V58 permits only an immutable role request linked to the exact durable `WAITING` source intent to remain pending; pending results contain no audit, member result or authorization. Once both owner outcomes permit the source change, role, membership/pair counters, authority event, audit and source completion commit in the same Account transaction. Retry reads the original source vector instead of recapturing later state, and issuance-fence invalidation participates in both the membership and independently captured Account scopes. Four actual-writer ordering/recovery cases and two retained-journal/migration cases are defined; their corrected PostgreSQL execution remains required. The actor UUID is still a row selector, not authenticated caller proof, and creator bootstrap, hosted-terms sources and authenticated owner-result producers remain open. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) independently executed the nine existing authorization-fence PostgreSQL cases successfully with no skips and an Account job success; that checkpoint predates this source-writer integration and does not prove its new cases. + The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. Independently parsed raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for source `c5fd96e935028b72182d58a611152bee6a8e533b`, records all nine fence methods passing once without skips, errors or failures. Account's Gradle Checks passed, but the job was cancelled at post-Gradle setup; the observer could not retrieve checkout logs while the aggregate remained active, and Game Design and World proof failed separately. These are executed Account storage cases, not a green composed boundary or proof of an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. Exact corrected Account head `3440d4d646414c2c7244e5e0cc1b650cd9e242d8` has executed [CI37290103027](https://github.com/benhook1013/FireMUD/actions/runs/37290103027) proof. Account job `111698347142` succeeded; the strict log records all fourteen `AccountAuthenticationUuidIntegrationTest` cases passing without skips, including one execution of the repaired email-OTP method. No separate OTP XML artifact was uploaded, so that method's attribution rests on the strict job log. All twenty required role/journal/fresh-JOIN/physical-mTLS methods also passed: independently parsed raw suites record JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. The actual Game Session client PostgreSQL/mTLS suite passed 3/3 without skips before its later full check was cancelled; Game Session job `111698347041` and aggregate CI therefore did not pass. The cancellation log supplies no causal explanation. Verified checkout merge `c82c0262d55106fcbea0ed2329adfb1ff19098f1` has the exact World `f968b46adf12570e870b17e17fe0d4382e7078b4` and Account source parents and the same source tree `d39693e551631ed21fb1a6751eb4c4c6658a0e8c`. This closes the OTP fixture execution gap and repeats the physical component proof on that composed tree; upstream caller/policy, current-parent alignment, complete authorization, fresh images, live readiness and activation remain independent gates. 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 0bde5cec8c..3d68e3e02c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The current publication candidate reuses one six-family database graph reader for both FROZEN capture and explicitly unwired OPEN region staging. OPEN staging resolves committed intake and V27 private keys under the existing owner lock, checks the enclosing commit's exact Game Design source provenance, and returns immutable unverified content without applying it or advancing synchronized visibility. Four database staging cases are defined; actual execution remains required. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) independently executed all eight publication-fence PostgreSQL cases successfully, while all four graph cases failed during fixture setup because independent committed intake readback ran before the intake transaction committed. The fixture now commits and reads back the real intake before owner resolution, preserving the canonical write guards and synthetic authentication prerequisites. Corrected execution remains open; staged representation and freeze storage still do not prove an authenticated owner apply, synchronized normal reads, release eligibility, fresh canonical content production or runtime topology materialization. + The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. The held-back World mutation algorithm now uses full-tuple, expected-epoch SQL predicates for its declared aggregate and scope advances. An absent epoch can be claimed only from zero with a conflict-safe insert; stale, negative or overflowing expected counters cannot succeed. A losing advance raises `DRAFT_WRITE_CONFLICT` inside the existing owner transaction rather than committing content under an unconditional epoch save. The focused mutation suite executed 29 cases successfully. The consolidated World check, boot JAR, formatting, static analysis, links and Markdown passed with 227 unit executions and no unit skips; all 55 PostgreSQL integration methods, including five new deterministic race, tuple-isolation and rollback cases, compiled but skipped locally without Docker. The subsequent exact-source CI execution is recorded below. This closes a local storage primitive, not complete affected-scope validation, immutable complete-input retry binding, source-qualified content materialization, synchronized Draft visibility, Account authorization, publication or lifecycle. The registered mutation remains denied. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) remains the target contract. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java index 27a201b2bd..410008700f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java @@ -3,6 +3,7 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -195,6 +196,84 @@ public byte[] canonicalBytes() { frame(output, evidence); return output.toByteArray(); } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + static final class FrameReader { + private final ByteBuffer input; + + FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + int remaining() { + return input.remaining(); + } + + void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } } public enum Owner { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index d72e58b5f0..b69f547ae2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -130,6 +130,37 @@ public byte[] canonicalBytes() { DraftAuthorizationFenceBinding.frame(out, mutation); return out.toByteArray(); } + + /** + * Exact recovery of the original vector; callers must never replace it with a fresh capture. + */ + public static SourceChange fromStored(byte[] stored) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect("account-draft-source-change/v1"); + String id = reader.text(); + DraftAuthorizationFenceBinding.canonicalUuid(id); + String count = reader.text(); + DraftAuthorizationFenceBinding.decimal(count, false); + final int size; + try { + size = Integer.parseInt(count); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Stored source count is out of range", invalid); + } + if (size > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int i = 0; i < size; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + SourceChange change = new SourceChange(UUID.fromString(id), sources, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, change.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source change"); + } + return change; + } } /** diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java index 9850fcd43e..b30a4fd530 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import org.jooq.DSLContext; import org.jooq.Record; @@ -37,7 +38,7 @@ public AccountTenantRoleOperationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); } - /** Claims a request in the caller's write transaction, or returns its exact committed result. */ + /** Claims a request, or returns its exact committed result or durable pending intent. */ @Transactional(propagation = Propagation.MANDATORY) public Claim claim(Request request) { requireWriteOwnerTransaction(); @@ -79,12 +80,67 @@ public Claim claim(Request request) { throw new OperationConflictException( "Tenant-role request ID was reused with changed immutable input"); } - if (!"COMMITTED".equals(existing.status())) { - throw new IllegalStateException("Incomplete tenant-role request is not replayable"); + if (!"COMMITTED".equals(existing.status()) && findSourceChangeForUpdate(request).isEmpty()) { + throw new IllegalStateException( + "Incomplete tenant-role request has no original source intent"); } return new Claim(false, Optional.of(existing)); } + /** Binds the original V57 vector to the request before its WAITING transaction may commit. */ + @Transactional(propagation = Propagation.MANDATORY) + public void captureSourceChange(Request request, SourceChange change) { + requireWriteOwnerTransaction(); + requireSourceRequest(request, change); + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET source_change_binding = ? " + + "WHERE request_id = ? AND status = 'IN_PROGRESS' " + + "AND request_payload = ? AND source_change_binding IS NULL", + change.canonicalBytes(), + request.requestId(), + request.payload()); + if (updated != 1 + || !Arrays.equals( + findSourceChangeForUpdate(request).orElseThrow().canonicalBytes(), + change.canonicalBytes())) { + throw new IllegalStateException("Tenant-role original source capture differs"); + } + } + + /** Returns the immutable original capture, including after process or response loss. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findSourceChangeForUpdate(Request request) { + requireWriteOwnerTransaction(); + Record row = + dsl.fetchOne( + "SELECT request_payload, source_change_binding FROM " + + OPERATIONS + + " WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (row == null + || !Arrays.equals(row.get("request_payload", byte[].class), request.payload())) { + throw new OperationConflictException("Tenant-role source request binding differs"); + } + byte[] stored = row.get("source_change_binding", byte[].class); + if (stored == null) { + return Optional.empty(); + } + SourceChange change = SourceChange.fromStored(stored); + requireSourceRequest(request, change); + return Optional.of(change); + } + + private static void requireSourceRequest(Request request, SourceChange change) { + if (!request.requestId().equals(change.changeId()) + || !Arrays.equals(request.payload(), change.mutation())) { + throw new OperationConflictException( + "Tenant-role original source intent differs from request"); + } + } + /** Completes a claimed request only after all mutation, event, and audit writes read back. */ @Transactional(propagation = Propagation.MANDATORY) public OperationEvidence complete( @@ -642,6 +698,11 @@ public byte[] requestPayload() { public byte[] resultPayload() { return resultPayload == null ? null : resultPayload.clone(); } + + /** Pending is a retained intent only; it carries no event, result, or authorization. */ + public boolean pending() { + return "IN_PROGRESS".equals(status); + } } public record Claim(boolean claimed, Optional replay) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java index ba68af972f..ca55d7f8d6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -11,6 +12,10 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -39,6 +44,8 @@ import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.TenantRoleEventEvidence; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.jooq.DSLContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -65,6 +72,7 @@ public class AccountTenantRoleMutationService { private final AccountTenantRoleOperationRepository operationRepository; private final AccountAuditOutboxRepository auditOutboxRepository; private final AccountMembershipAuthorityEventProducer eventProducer; + private final DraftAuthorizationFenceRepository draftFenceRepository; @SuppressFBWarnings( value = "CT_CONSTRUCTOR_THROW", @@ -80,7 +88,8 @@ public AccountTenantRoleMutationService( AccountMembershipPairAuthorityRepository pairAuthorityRepository, AccountTenantRoleOperationRepository operationRepository, AccountAuditOutboxRepository auditOutboxRepository, - AccountMembershipAuthorityEventProducer eventProducer) { + AccountMembershipAuthorityEventProducer eventProducer, + DSLContext dsl) { this.accountRepository = Objects.requireNonNull(accountRepository); this.tenantIdentityResolver = Objects.requireNonNull(tenantIdentityResolver); this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); @@ -90,11 +99,13 @@ public AccountTenantRoleMutationService( this.operationRepository = Objects.requireNonNull(operationRepository); this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository); this.eventProducer = Objects.requireNonNull(eventProducer); + this.draftFenceRepository = new DraftAuthorizationFenceRepository(dsl); } /** - * Applies one role-source mutation inside a single Account write transaction. No transport or - * authenticated actor proof is accepted here; public Account/runtime ingress remains denied. + * Applies one role-source mutation, or commits only its original pending source intent when Draft + * participants have not settled. A pending result has no member, audit or authorization evidence. + * No transport or authenticated actor proof is accepted here; public ingress remains denied. */ @Transactional public OperationEvidence mutate(Request request) { @@ -117,9 +128,13 @@ public OperationEvidence mutate(Request request) { AccountTenantRoleOperationRepository.Claim claim = operationRepository.claim(request); if (!claim.claimed()) { OperationEvidence replay = claim.replay().orElseThrow(); - verifyExactReplay(replay); - return replay; + if (!replay.pending()) { + verifyExactReplay(replay); + return replay; + } } + SourceChange originalChange = + operationRepository.findSourceChangeForUpdate(request).orElse(null); // The tenant generation row is the shared-source serialization point for same-tenant writes. for (UUID accountUuid : orderedAccountUuids) { @@ -164,7 +179,7 @@ public OperationEvidence mutate(Request request) { .sorted(Comparator.comparing(change -> change.accountUuid().toString())) .toList(); - List memberResults = new ArrayList<>(); + List preparedChanges = new ArrayList<>(); for (RoleChange change : orderedChanges) { AccountTenantMembership membership = membershipRepository @@ -213,6 +228,40 @@ public OperationEvidence mutate(Request request) { } if (change.invalidated()) { increment(authority.issuanceFence().value(), "issuance fence"); + increment(authority.issuanceFence().sourceVersion(), "issuance fence source version"); + increment(memberState.generation(), "membership authority generation"); + increment(memberState.sourceVersion(), "membership authority source version"); + } + increment(membership.getMembershipVersion(), "membership version"); + preparedChanges.add(new PreparedChange(change, membership, pair, authority)); + } + + // Actual Account source rows remain locked through capture, ordering and any source commit. + // An exact pending retry revalidates against, but never replaces, its original stored vector. + SourceChange currentChange = sourceChange(request, preparedChanges); + SourceChange sourceChange = originalChange == null ? currentChange : originalChange; + if (!Arrays.equals(sourceChange.canonicalBytes(), currentChange.canonicalBytes())) { + throw new AccountTenantRoleOperationRepository.OperationConflictException( + "Tenant-role current source differs from its original pending capture"); + } + boolean settled = draftFenceRepository.requestSourceChange(sourceChange); + if (originalChange == null) { + operationRepository.captureSourceChange(request, sourceChange); + } + if (!settled || !draftFenceRepository.sourceMutationPermitted(sourceChange)) { + // Returning normally is essential: V57's WAITING revocation and the immutable role request + // must survive a retry/process loss rather than rolling back with a thrown denial. + return operationRepository.findForUpdate(request.requestId()).orElseThrow(); + } + + List memberResults = new ArrayList<>(); + for (PreparedChange prepared : preparedChanges) { + RoleChange change = prepared.change(); + AccountTenantMembership membership = prepared.membership(); + PairAuthority pair = prepared.pair(); + CompositeSnapshot authority = prepared.authority(); + ScopeState memberState = authority.memberships().getFirst(); + if (change.invalidated()) { memberState = authorityGenerationRepository.advance(memberState, authority.issuanceFence()); } @@ -270,6 +319,7 @@ public OperationEvidence mutate(Request request) { auditEnvelope.occurredAt(), auditEnvelope.payloadDigest(), auditEnvelope.payload().getBytes(StandardCharsets.UTF_8)); + draftFenceRepository.markSourceCommitted(sourceChange); OperationEvidence completed = operationRepository.complete(request, auditEvidence, memberResults); @@ -306,6 +356,74 @@ public OperationEvidence mutate(Request request) { return completed; } + private SourceChange sourceChange(Request request, List preparedChanges) { + List sources = new ArrayList<>(); + for (PreparedChange prepared : preparedChanges) { + RoleChange change = prepared.change(); + CompositeSnapshot authority = prepared.authority(); + ScopeState membership = authority.memberships().getFirst(); + var event = change.current().authorityEvent(); + sources.add( + new SourceEvidence( + SourceKind.MEMBERSHIP, + change.accountUuid() + "/" + request.tenantUuid(), + Long.toString(membership.generation()), + Long.toString(membership.sourceVersion()), + event.outboxStreamKey(), + event.outboxSequence(), + event.canonicalJsonUtf8())); + if (change.invalidated()) { + // Membership invalidation also changes this Account's issuance fence. ACCOUNT participation + // therefore uses the actual independent Account source state and its actual checkpoint, + // with both issuance-fence counters bound separately in the evidence; no counter aliasing. + ScopeState account = authority.account(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + change.accountUuid(); + var checkpoint = + change.current().outboxCheckpoints().stream() + .filter(candidate -> stream.equals(candidate.outboxStreamKey())) + .findFirst() + .orElseThrow( + () -> new IllegalStateException("Account source checkpoint is absent")); + var sourceEvent = + change.current().outboxSourceEvidence().stream() + .filter(candidate -> stream.equals(candidate.outboxStreamKey())) + .findFirst(); + if ("0".equals(checkpoint.outboxSequence()) == sourceEvent.isPresent() + || (sourceEvent.isPresent() + && !checkpoint + .outboxSequence() + .equals(sourceEvent.orElseThrow().outboxSequence()))) { + throw new IllegalStateException("Account source event and checkpoint differ"); + } + byte[] evidence = + AUDIT_JSON + .writeValueAsString( + new AccountFenceCapture( + "account-tenant-role-issuance-source/v1", + change.accountUuid().toString(), + Long.toString(account.generation()), + Long.toString(account.sourceVersion()), + Long.toString(authority.issuanceFence().value()), + Long.toString(authority.issuanceFence().sourceVersion()), + stream, + checkpoint.outboxSequence(), + sourceEvent.map(candidate -> candidate.canonicalEventJson()).orElse(null))) + .getBytes(StandardCharsets.UTF_8); + sources.add( + new SourceEvidence( + SourceKind.ACCOUNT, + change.accountUuid().toString(), + Long.toString(account.generation()), + Long.toString(account.sourceVersion()), + stream, + checkpoint.outboxSequence(), + evidence)); + } + } + return new SourceChange(request.requestId(), sources, request.payload()); + } + private Map roleChanges( Request request, PositiveMembershipSnapshot actor, PositiveMembershipSnapshot target) { Map changes = new LinkedHashMap<>(); @@ -384,6 +502,15 @@ private void verifyExactReplay(OperationEvidence operation) { if (!"COMMITTED".equals(operation.status()) || operation.audit() == null) { throw new IllegalStateException("Tenant-role exact retry lacks committed immutable evidence"); } + operationRepository + .findSourceChangeForUpdate(operation.request()) + .ifPresent( + change -> { + if (!"SOURCE_COMMITTED" + .equals(draftFenceRepository.readSourceChange(change).status())) { + throw new IllegalStateException("Tenant-role committed source readback differs"); + } + }); AuditEvidence audit = operation.audit(); auditOutboxRepository .findCanonicalTenantRoleEnvelopeForUpdate( @@ -502,6 +629,23 @@ private record RoleChange( List roles, boolean invalidated) {} + private record PreparedChange( + RoleChange change, + AccountTenantMembership membership, + PairAuthority pair, + CompositeSnapshot authority) {} + + private record AccountFenceCapture( + String schema, + String accountId, + String generation, + String sourceVersion, + String issuanceFence, + String issuanceFenceSourceVersion, + String checkpointStream, + String checkpointSequence, + String canonicalEventJson) {} + private record AuditPayload( String schema, String requestId, diff --git a/services/account-service/src/main/resources/db/migration/V58__tenant_role_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V58__tenant_role_pending_draft_source_changes.sql new file mode 100644 index 0000000000..85311e1a43 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V58__tenant_role_pending_draft_source_changes.sql @@ -0,0 +1,162 @@ +-- Preserve V56 committed history; only a request bound to an exact V57 WAITING intent may remain +-- pending. No authenticated actor, public route, or hosted-terms producer is enabled here. +ALTER TABLE account_tenant_role_operations ADD COLUMN source_change_binding BYTEA; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_tenant_role_operation_update_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.schema_version IS DISTINCT FROM OLD.schema_version + OR NEW.actor_account_uuid IS DISTINCT FROM OLD.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.target_account_uuid IS DISTINCT FROM OLD.target_account_uuid + OR NEW.action IS DISTINCT FROM OLD.action + OR NEW.expected_actor_membership_version IS DISTINCT FROM OLD.expected_actor_membership_version + OR NEW.expected_target_membership_version IS DISTINCT FROM OLD.expected_target_membership_version + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR OLD.status <> 'IN_PROGRESS' THEN + RAISE EXCEPTION 'Account tenant-role operation request is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_identity_immutable'; + END IF; + + IF OLD.source_change_binding IS NULL AND NEW.source_change_binding IS NOT NULL + AND NEW.status = 'IN_PROGRESS' THEN + IF NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.request_id AND status = 'WAITING' + AND binding = NEW.source_change_binding) + OR octet_length(NEW.source_change_binding) < octet_length(NEW.request_payload) + 4 + OR substring(NEW.source_change_binding FROM + octet_length(NEW.source_change_binding) - octet_length(NEW.request_payload) - 3) + IS DISTINCT FROM int4send(octet_length(NEW.request_payload)) || NEW.request_payload THEN + RAISE EXCEPTION 'Tenant-role pending capture must bind the exact V57 request intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_pending_source_binding'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status <> 'COMMITTED' + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding THEN + RAISE EXCEPTION 'Account tenant-role source capture and result are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_identity_immutable'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_role_source_capture_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.source_change_binding IS NOT NULL THEN + RAISE EXCEPTION 'Tenant-role source capture must follow the exact V57 source-change claim' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_pending_source_binding'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_role_source_capture_insert + BEFORE INSERT ON account_tenant_role_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_source_capture_insert_guard(); + +CREATE OR REPLACE FUNCTION account_tenant_role_operation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_operation account_tenant_role_operations%ROWTYPE; + member_count BIGINT; + source_status TEXT; +BEGIN + SELECT * INTO current_operation FROM account_tenant_role_operations + WHERE request_id = NEW.request_id; + SELECT count(*) INTO member_count FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id; + + IF current_operation.source_change_binding IS NOT NULL THEN + SELECT status INTO source_status FROM account_draft_authorization_source_changes + WHERE change_id = current_operation.request_id + AND binding = current_operation.source_change_binding; + IF source_status IS NULL THEN + RAISE EXCEPTION 'Tenant-role operation lacks its immutable V57 source intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_pending_source_binding'; + END IF; + END IF; + IF current_operation.status = 'IN_PROGRESS' THEN + IF source_status = 'WAITING' AND member_count = 0 THEN + RETURN NULL; + END IF; + RAISE EXCEPTION 'Incomplete Account tenant-role operation cannot commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_must_complete'; + END IF; + IF source_status IS NOT NULL AND source_status <> 'SOURCE_COMMITTED' THEN + RAISE EXCEPTION 'Tenant-role result requires the same owner transaction source commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_pending_source_binding'; + END IF; + + IF (current_operation.action = 'TRANSFER_TENANT_ADMIN' AND member_count <> 2) + OR (current_operation.action <> 'TRANSFER_TENANT_ADMIN' AND member_count <> 1) THEN + RAISE EXCEPTION 'Account tenant-role operation has an incomplete member result' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_member_result_count'; + END IF; + IF current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND (NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.actor_account_uuid + AND tenant_uuid = current_operation.tenant_uuid) + OR NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid)) + OR current_operation.action IN ('GRANT_DESIGNER', 'REVOKE_DESIGNER') + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid) THEN + RAISE EXCEPTION 'Account tenant-role operation member identities differ from its request' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_member_identity'; + END IF; + IF (current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.actor_account_uuid + AND tenant_uuid = current_operation.tenant_uuid AND caller_bound_authority_invalidated) + OR current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid AND NOT caller_bound_authority_invalidated) + OR current_operation.action IN ('GRANT_DESIGNER', 'REVOKE_DESIGNER') + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid + AND caller_bound_authority_invalidated = (current_operation.action = 'REVOKE_DESIGNER'))) THEN + RAISE EXCEPTION 'Account tenant-role operation invalidation evidence differs from action' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_operation_invalidation_shape'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_role_linked_source_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM account_tenant_role_operations operation + WHERE operation.request_id = NEW.change_id + AND operation.source_change_binding IS NOT NULL + AND (operation.source_change_binding IS DISTINCT FROM NEW.binding + OR (NEW.status = 'SOURCE_COMMITTED' AND operation.status <> 'COMMITTED'))) THEN + RAISE EXCEPTION 'Linked tenant-role source and operation must commit together' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_role_pending_source_binding'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_tenant_role_linked_source_complete + AFTER UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_linked_source_complete_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 7ff58f77e4..241d348f8d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -29,6 +29,15 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -77,6 +86,10 @@ import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.v1.GameplayRealm; @@ -141,6 +154,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoSpyBean private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; @Autowired private AccountMembershipLifecycleService membershipLifecycleService; @Autowired private AccountTenantRoleMutationService tenantRoleMutationService; + @Autowired private AccountTenantRoleOperationRepository tenantRoleOperationRepository; @MockitoSpyBean private AccountAuthorityOutboxRepository authorityOutboxRepository; @MockitoSpyBean private AccountAuditOutboxRepository auditOutboxRepository; @Autowired private PlatformTransactionManager transactionManager; @@ -1982,6 +1996,414 @@ void invalidatingTenantRoleMutationDeniesFenceOverflowWithoutChangingAnyAccountS assertTenantRoleOperationAbsent(requestId); } + @Test + void tenantRoleSourceWaitsForBothCommittedOwnersAndRecoversOriginalPendingCapture() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Request request = roleRequest(fixture, Action.GRANT_DESIGNER, 2L); + DraftAuthorizationFenceBinding binding = + syntheticVerifiedRoleFence(fixture.target(), SourceKind.MEMBERSHIP); + reserveRoleFence(binding, true); + Map before = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long audits = countAuditOutboxRows(fixture.admin()); + + OperationEvidence pending = tenantRoleMutationService.mutate(request); + assertPendingRoleIntent(pending); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(before); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(audits); + SourceChange captured = originalRoleSourceChange(request); + assertThat(captured.mutation()).containsExactly(request.payload()); + assertThat(captured.sources()).hasSize(1); + assertThat(captured.sources().getFirst().sourceVersion()).isEqualTo("1"); + assertThat(captured.sources().getFirst().evidence()) + .containsExactly( + readExistingPairBoundPositiveMembershipSnapshot(fixture.target()) + .authorityEvent() + .canonicalJsonUtf8()); + + syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); + assertPendingRoleIntent(restartedRoleMutation(request)); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(captured.canonicalBytes()); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(before); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(audits); + + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.COMMITTED); + OperationEvidence committed = restartedRoleMutation(request); + assertThat(committed.pending()).isFalse(); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertCurrentRoleMutationState( + fixture.target(), 3L, 1L, 2L, 1L, List.of("designer", "player"), false); + assertExactTenantRoleOperation(committed, tenantRoleMutationService.mutate(request)); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(captured.canonicalBytes()); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + new DraftAuthorizationFenceRepository(dsl) + .readSourceChange(captured) + .status())) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void tenantRoleRevocationWinsOrderButWaitsForBothFencedAbortReadbacks() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + assertThat( + tenantRoleMutationService + .mutate(roleRequest(fixture, Action.GRANT_DESIGNER, 2L)) + .status()) + .isEqualTo("COMMITTED"); + Request request = roleRequest(fixture, Action.REVOKE_DESIGNER, 3L); + DraftAuthorizationFenceBinding binding = + syntheticVerifiedRoleFence(fixture.target(), SourceKind.MEMBERSHIP); + reserveRoleFence(binding, false); + Map before = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); + SourceChange captured = originalRoleSourceChange(request); + assertThat(captured.sources().stream().map(SourceEvidence::key).toList()) + .containsExactly( + "ACCOUNT:" + fixture.target().accountUuid(), + "MEMBERSHIP:" + fixture.target().accountUuid() + "/" + fixture.target().tenantUuid()); + SourceEvidence account = captured.sources().getFirst(); + assertThat(account.sourceVersion()).isEqualTo("1"); + assertThat(account.checkpointSequence()).isEqualTo("0"); + assertThat(new String(account.evidence(), StandardCharsets.UTF_8)) + .contains( + "\"sourceVersion\":\"1\"", + "\"issuanceFence\":\"1\"", + "\"issuanceFenceSourceVersion\":\"1\""); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> new DraftAuthorizationFenceRepository(dsl).read(binding).ordering())) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> + new TransactionTemplate(transactionManager) + .execute( + status -> + new DraftAuthorizationFenceRepository(dsl).claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + assertPendingRoleIntent(restartedRoleMutation(request)); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(before); + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(restartedRoleMutation(request).status()).isEqualTo("COMMITTED"); + assertCurrentRoleMutationState(fixture.target(), 4L, 2L, 3L, 2L, List.of("player"), true); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(captured.canonicalBytes()); + } + + @Test + void tenantRoleTransferParticipatesInBothMembershipsAndAccountIssuanceScope() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Request request = roleRequest(fixture, Action.TRANSFER_TENANT_ADMIN, 2L); + DraftAuthorizationFenceBinding actor = + syntheticVerifiedRoleFence(fixture.admin(), SourceKind.MEMBERSHIP); + DraftAuthorizationFenceBinding target = + syntheticVerifiedRoleFence(fixture.target(), SourceKind.MEMBERSHIP); + DraftAuthorizationFenceBinding issuance = + syntheticVerifiedRoleFence(fixture.admin(), SourceKind.ACCOUNT); + for (DraftAuthorizationFenceBinding binding : List.of(actor, target, issuance)) { + reserveRoleFence(binding, true); + } + assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); + SourceChange original = originalRoleSourceChange(request); + assertThat(original.sources().stream().map(SourceEvidence::key).toList()) + .containsExactlyInAnyOrder( + "MEMBERSHIP:" + fixture.admin().accountUuid() + "/" + fixture.admin().tenantUuid(), + "MEMBERSHIP:" + fixture.target().accountUuid() + "/" + fixture.target().tenantUuid(), + "ACCOUNT:" + fixture.admin().accountUuid()); + for (DraftAuthorizationFenceBinding binding : List.of(actor, target)) { + syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); + } + syntheticVerifiedOwnerReadback(issuance, Owner.WORLD, Outcome.COMMITTED); + assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); + assertThat(committedRoles(fixture.admin())).contains("tenantAdmin"); + assertThat(committedRoles(fixture.target())).doesNotContain("tenantAdmin"); + syntheticVerifiedOwnerReadback(issuance, Owner.GAME_DESIGN, Outcome.COMMITTED); + OperationEvidence transfer = tenantRoleMutationService.mutate(request); + assertThat(transfer.status()).isEqualTo("COMMITTED"); + assertThat(transfer.members()).hasSize(2); + assertCurrentRoleMutationState(fixture.admin(), 3L, 2L, 2L, 2L, List.of("player"), true); + assertCurrentRoleMutationState( + fixture.target(), 3L, 1L, 2L, 1L, List.of("player", "tenantAdmin"), false); + } + + @Test + void tenantRolePendingRetryRejectsChangedIdentityAndNeverRecapturesLaterSource() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Request request = roleRequest(fixture, Action.GRANT_DESIGNER, 2L); + DraftAuthorizationFenceBinding binding = + syntheticVerifiedRoleFence(fixture.target(), SourceKind.MEMBERSHIP); + reserveRoleFence(binding, true); + assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); + SourceChange original = originalRoleSourceChange(request); + for (Request changed : + List.of( + new Request( + request.requestId(), + request.actorAccountUuid(), + UUID.randomUUID(), + request.targetAccountUuid(), + request.action(), + 2L, + 2L), + new Request( + request.requestId(), + request.actorAccountUuid(), + request.tenantUuid(), + request.actorAccountUuid(), + request.action(), + 2L, + 2L), + new Request( + request.requestId(), + request.targetAccountUuid(), + request.tenantUuid(), + request.targetAccountUuid(), + request.action(), + 2L, + 2L), + new Request( + request.requestId(), + request.actorAccountUuid(), + request.tenantUuid(), + request.targetAccountUuid(), + request.action(), + 3L, + 2L), + new Request( + request.requestId(), + request.actorAccountUuid(), + request.tenantUuid(), + request.targetAccountUuid(), + Action.REVOKE_DESIGNER, + 2L, + 2L))) { + assertThatThrownBy(() -> tenantRoleMutationService.mutate(changed)) + .isInstanceOf(AccountTenantRoleOperationRepository.OperationConflictException.class); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + } + syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.COMMITTED); + // A separately identified source writer wins the same original version after settlement. + assertThat( + tenantRoleMutationService + .mutate(roleRequest(fixture, Action.GRANT_DESIGNER, 2L)) + .status()) + .isEqualTo("COMMITTED"); + Map afterWinner = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + assertThatThrownBy(() -> restartedRoleMutation(request)) + .isInstanceOf(AccountTenantRoleOperationRepository.OperationConflictException.class) + .hasMessageContaining("membership version is stale"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(afterWinner); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + new DraftAuthorizationFenceRepository(dsl) + .readSourceChange(original) + .status())) + .isEqualTo("WAITING"); + } + + private Request roleRequest(TenantRoleFixture fixture, Action action, long targetVersion) { + return new Request( + UUID.randomUUID(), + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + action, + 2L, + targetVersion); + } + + private void assertPendingRoleIntent(OperationEvidence pending) { + assertThat(pending.pending()).isTrue(); + assertThat(pending.status()).isEqualTo("IN_PROGRESS"); + assertThat(pending.members()).isEmpty(); + assertThat(pending.audit()).isNull(); + assertThat(pending.resultPayload()).isNull(); + assertThat(pending.resultDigest()).isNull(); + } + + private SourceChange originalRoleSourceChange(Request request) { + return Objects.requireNonNull( + new TransactionTemplate(transactionManager) + .execute( + status -> + tenantRoleOperationRepository + .findSourceChangeForUpdate(request) + .orElseThrow())); + } + + private OperationEvidence restartedRoleMutation(Request request) { + // Recreate the actual source writer: recovery depends on its database vector, not object + // memory. + return Objects.requireNonNull( + new TransactionTemplate(transactionManager) + .execute( + status -> + new AccountTenantRoleMutationService( + accountRepository, + tenantIdentityResolver, + authorityGenerationRepository, + membershipRepository, + roleSnapshotRepository, + pairAuthorityRepository, + tenantRoleOperationRepository, + auditOutboxRepository, + membershipAuthorityEventProducer, + dsl) + .mutate(request))); + } + + /** + * Synthetic verified Draft-capture prerequisites only. Membership/source counters come from the + * real Account snapshot, but fixture target/actor verification and owner authentication are + * stipulated; these cases prove the actual role writer's ordering, not an authenticated producer. + */ + private DraftAuthorizationFenceBinding syntheticVerifiedRoleFence( + JoinFixture fixture, SourceKind kind) { + return Objects.requireNonNull( + new TransactionTemplate(transactionManager) + .execute( + status -> { + PositiveMembershipSnapshot snapshot = + membershipAuthorityEventProducer + .readCurrentPairBoundPositiveMembershipSnapshot( + fixture.accountId(), fixture.tenantId()); + var authority = + authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + fixture.accountUuid(), + List.of(fixture.tenantUuid()), + List.of(fixture.tenantUuid())); + SourceEvidence source; + if (kind == SourceKind.MEMBERSHIP) { + var membership = authority.memberships().getFirst(); + var event = snapshot.authorityEvent(); + source = + new SourceEvidence( + kind, + fixture.accountUuid() + "/" + fixture.tenantUuid(), + Long.toString(membership.generation()), + Long.toString(membership.sourceVersion()), + event.outboxStreamKey(), + event.outboxSequence(), + event.canonicalJsonUtf8()); + } else { + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + fixture.accountUuid(); + var checkpoint = + snapshot.outboxCheckpoints().stream() + .filter(candidate -> stream.equals(candidate.outboxStreamKey())) + .findFirst() + .orElseThrow(); + source = + new SourceEvidence( + kind, + fixture.accountUuid().toString(), + Long.toString(authority.account().generation()), + Long.toString(authority.account().sourceVersion()), + stream, + checkpoint.outboxSequence(), + ("synthetic-verified-issuance-scope:" + + authority.issuanceFence().value() + + ":" + + authority.issuanceFence().sourceVersion()) + .getBytes(StandardCharsets.UTF_8)); + } + UUID version = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + fixture.tenantUuid(), + version, + fixture.tenantId(), + "synthetic-role-tenant", + 2L, + "synthetic-role-tenant", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "synthetic-role-base", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "synthetic-role-input")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "role-region", + "aggregate", + "role-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + fixture.accountUuid(), + fixture.tenantUuid(), + version, + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + })); + } + + private void reserveRoleFence(DraftAuthorizationFenceBinding binding, boolean commitOrder) { + new TransactionTemplate(transactionManager) + .execute( + status -> { + var repository = new DraftAuthorizationFenceRepository(dsl); + repository.reserve(binding); + if (commitOrder) { + repository.claimCommitOrder(binding); + } + return null; + }); + } + + /** Fixture stipulates exact authenticated owner verification; it is not network proof. */ + private void syntheticVerifiedOwnerReadback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + new TransactionTemplate(transactionManager) + .execute( + status -> { + new DraftAuthorizationFenceRepository(dsl) + .recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + ("synthetic-verified-owner:" + owner + ":" + outcome) + .getBytes(StandardCharsets.UTF_8))); + return null; + }); + } + @Test void concurrentOpposingTenantAdminTransfersLeaveOneCurrentAdministrator() throws Exception { TenantRoleFixture fixture = syntheticRetainedAdminFixture(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java index 59707eb6d0..8ecdb6d1c9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java @@ -10,6 +10,10 @@ import java.util.Objects; import java.util.UUID; import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest.MemberResult; import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; @@ -135,6 +139,126 @@ void immutableJournalRetriesOriginalBytesAfterLaterRoleOperationAndRejectsChange .isInstanceOf(org.jooq.exception.DataAccessException.class); } + @Test + void forwardPendingMigrationPreservesExistingV56CommittedResultExactly() { + TestContext context = newTestContext("56"); + UUID actor = insertAccount(context.setupDsl()); + UUID target = insertAccount(context.setupDsl()); + Request request = + request(UUID.randomUUID(), actor, UUID.randomUUID(), target, Action.GRANT_DESIGNER, 4L, 7L); + OperationEvidence original = + inTransaction( + context.transaction(), + () -> { + context.repository().claim(request); + return context + .repository() + .complete( + request, + audit(UUID.randomUUID(), "{\"v56\":true}"), + List.of( + member( + request, target, 8L, 1L, 1L, List.of("designer", "player"), false))); + }); + String schema = + context.setupDsl().resultQuery("SELECT current_schema()").fetchOne(0, String.class); + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + OperationEvidence replay = + inTransaction( + context.transaction(), + () -> context.repository().claim(request).replay().orElseThrow()); + assertExactOperation(original, replay); + assertThat( + this.>inTransaction( + context.transaction(), + () -> context.repository().findSourceChangeForUpdate(request))) + .isEmpty(); + } + + @Test + void onlyExactLinkedWaitingIntentMayPersistAndItsCaptureCannotBeChanged() { + TestContext context = newTestContext(); + UUID actor = insertAccount(context.setupDsl()); + UUID target = insertAccount(context.setupDsl()); + Request request = + request(UUID.randomUUID(), actor, UUID.randomUUID(), target, Action.GRANT_DESIGNER, 4L, 7L); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> context.repository().claim(request))) + .isInstanceOf(org.springframework.transaction.TransactionException.class); + // Synthetic verified source prerequisites: storage/recovery proof, not authenticated capture. + SourceChange original = + new SourceChange( + request.requestId(), + List.of( + new SourceEvidence( + SourceKind.MEMBERSHIP, + target + "/" + request.tenantUuid(), + "1", + "922337203685477580812345", + "synthetic-membership-stream", + "0", + new byte[] {1})), + request.payload()); + var fences = + new DraftAuthorizationFenceRepository( + DSL.using( + new TransactionAwareDataSourceProxy(context.dataSource()), SQLDialect.POSTGRES)); + inTransaction( + context.transaction(), + () -> { + context.repository().claim(request); + fences.requestSourceChange(original); + context.repository().captureSourceChange(request, original); + return null; + }); + OperationEvidence pending = + inTransaction( + context.transaction(), + () -> context.repository().claim(request).replay().orElseThrow()); + assertThat(pending.pending()).isTrue(); + assertThat(pending.members()).isEmpty(); + assertThat(pending.audit()).isNull(); + assertThat( + this.inTransaction( + context.transaction(), + () -> + context + .repository() + .findSourceChangeForUpdate(request) + .orElseThrow() + .canonicalBytes())) + .containsExactly(original.canonicalBytes()); + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "UPDATE account_tenant_role_operations SET source_change_binding = ? WHERE request_id = ?", + new byte[] {2}, + request.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + fences.markSourceCommitted(original); + return null; + })) + .isInstanceOf(org.springframework.transaction.TransactionException.class); + assertThat( + this.inTransaction( + context.transaction(), () -> fences.readSourceChange(original).status())) + .isEqualTo("WAITING"); + } + @Test void operationJournalAndMemberEvidenceRollBackTogether() { TestContext context = newTestContext(); @@ -189,20 +313,27 @@ void operationJournalAndMemberEvidenceRollBackTogether() { } private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContext(String targetVersion) { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(postgres.getJdbcUrl()); dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + migration.target(targetVersion); + } + migration.load().migrate(); DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); DSLContext transactionDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java index d912c83678..bf61abf915 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java @@ -19,6 +19,48 @@ import org.junit.jupiter.api.Test; class DraftAuthorizationFenceBindingTest { + @Test + void originalSourceChangeRoundTripsWithoutNarrowingIndependentCounters() { + SourceEvidence source = + new SourceEvidence( + SourceKind.MEMBERSHIP, + UUID.randomUUID() + "/" + UUID.randomUUID(), + "922337203685477580812345", + "922337203685477581812345", + "membership-stream", + "922337203685477583812345", + "unchanged-original-event".getBytes(StandardCharsets.UTF_8)); + SourceChange original = + new SourceChange(UUID.randomUUID(), List.of(source), new byte[] {1, 2, 3}); + SourceChange recovered = SourceChange.fromStored(original.canonicalBytes()); + assertThat(recovered.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(recovered.sources().getFirst().generation()).isEqualTo(source.generation()); + assertThat(recovered.sources().getFirst().sourceVersion()).isEqualTo(source.sourceVersion()); + assertThat(recovered.sources().getFirst().checkpointSequence()) + .isEqualTo(source.checkpointSequence()); + assertThat(recovered.mutation()).containsExactly(original.mutation()); + } + + @Test + void originalSourceChangeRejectsMalformedFramesAndNoncanonicalRecoveryBytes() { + SourceChange original = new SourceChange(UUID.randomUUID(), List.of(source()), new byte[] {1}); + byte[] stored = original.canonicalBytes(); + assertThatThrownBy( + () -> SourceChange.fromStored(java.util.Arrays.copyOf(stored, stored.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> SourceChange.fromStored(java.util.Arrays.copyOf(stored, stored.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + byte[] negativeSize = stored.clone(); + java.nio.ByteBuffer.wrap(negativeSize).putInt(-1); + assertThatThrownBy(() -> SourceChange.fromStored(negativeSize)) + .isInstanceOf(IllegalArgumentException.class); + byte[] impossibleSize = stored.clone(); + java.nio.ByteBuffer.wrap(impossibleSize).putInt(Integer.MAX_VALUE); + assertThatThrownBy(() -> SourceChange.fromStored(impossibleSize)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void copiedSourceListsAndEvidenceCannotRewriteBindingOrSourceChange() { byte[] evidence = new byte[] {1, 2}; diff --git a/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql new file mode 100644 index 0000000000..5f3b79686d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql @@ -0,0 +1,5 @@ +-- Full-version attempts retain the exact authored-Draft selection digest, +-- including its algorithm prefix. Widen only; preserve every existing attempt +-- and its original request digest, including absent historical evidence. +ALTER TABLE publish_attempt + ALTER COLUMN request_digest TYPE VARCHAR(71); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java index 542e82cc86..dff92e5d84 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java @@ -67,6 +67,73 @@ static void setUpSchema() { fixture = createFixture(); } + @Test + void v45PreservesRetainedAttemptDigestsAndStoresExactSelectionDigest() { + Fixture retained = createFixture("44"); + VersionFixture version = retained.newVersion(1L); + for (int index = 0; index < 3; index++) { + retained + .dsl() + .execute( + "INSERT INTO publish_attempt " + + "(tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, request_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + version.target().gameDesignVersionTenantKey(), + "retained-attempt-" + index, + index == 2 ? "SCRIPT_PATCH" : "FULL_VERSION", + index == 0 ? "PENDING" : index == 1 ? "SUCCEEDED" : "FAILED", + version.rowId(), + 1, + index == 2 ? null : "a".repeat(64)); + } + List> before = + retained.dsl().fetch("SELECT * FROM publish_attempt ORDER BY id").intoMaps(); + assertThat(before).hasSize(3); + + migrate(retained.dataSource(), retained.schema(), "45"); + + assertThat(retained.dsl().fetch("SELECT * FROM publish_attempt ORDER BY id").intoMaps()) + .isEqualTo(before); + assertThat( + retained + .dsl() + .fetchValue( + "SELECT character_maximum_length FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = 'publish_attempt' " + + "AND column_name = 'request_digest'", + retained.schema())) + .isEqualTo(71); + DraftCommitBinding commit = binding(version.target(), UUID.randomUUID(), UUID.randomUUID()); + retained.synchronize(commit); + SelectionSnapshot selected = reserve(retained, intent(version, commit, "exact selection")); + String workflowId = "selected-attempt-" + UUID.randomUUID(); + retained + .dsl() + .execute( + "INSERT INTO publish_attempt " + + "(tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, request_digest) VALUES (?, ?, 'FULL_VERSION', 'PENDING', ?, 1, ?)", + version.target().gameDesignVersionTenantKey(), + workflowId, + version.rowId(), + selected.selection().digest()); + assertThat( + retained + .dsl() + .fetchValue( + "SELECT request_digest FROM publish_attempt WHERE publish_workflow_id = ?", + workflowId)) + .isEqualTo(selected.selection().digest()); + assertThat( + retained + .dsl() + .fetch( + "SELECT * FROM publish_attempt WHERE publish_workflow_id <> ? ORDER BY id", + workflowId) + .intoMaps()) + .isEqualTo(before); + } + @Test void v44PreservesExactSelectionsRetainedAtV43() { Fixture retained = createFixture("43"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java index 5b008b881a..8956b4f184 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java @@ -2,18 +2,35 @@ import java.math.BigDecimal; import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.function.Function; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** Immutable World-owned value and codec for the six version-scoped authored content families. */ public final class WorldAuthoredGraph { private static final int SNAPSHOT_SCHEMA_VERSION = 1; + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); private final List> regions; private final List> zones; @@ -81,6 +98,315 @@ public byte[] encode(ObjectMapper objectMapper) { } } + /** + * Decodes only the exact canonical representation emitted by {@link #encode(ObjectMapper)}. This + * validates stored representation, not graph relationships or publication eligibility. + */ + static WorldAuthoredGraph decode(byte[] encoded, ObjectMapper objectMapper) { + if (encoded == null || objectMapper == null) { + throw malformed("World authored graph bytes or mapper are missing"); + } + byte[] original = encoded.clone(); + String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(original)) + .toString(); + } catch (CharacterCodingException exception) { + throw malformed("World authored graph bytes are not valid UTF-8", exception); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(json); + } catch (JacksonException exception) { + throw malformed("World authored graph bytes are not strict JSON", exception); + } + requireObject(root, "root"); + requireFields( + root, + "root", + "snapshotSchemaVersion", + "regions", + "zones", + "rooms", + "roomExits", + "generationRules", + "worldEntitySpawnBindings"); + JsonNode schemaVersion = root.get("snapshotSchemaVersion"); + if (!schemaVersion.isInt() || schemaVersion.intValue() != SNAPSHOT_SCHEMA_VERSION) { + throw malformed("World authored graph snapshot schema version is unsupported"); + } + + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + decodeRows(root.get("regions"), "regions", WorldAuthoredGraph::decodeRegion), + decodeRows(root.get("zones"), "zones", WorldAuthoredGraph::decodeZone), + decodeRows(root.get("rooms"), "rooms", WorldAuthoredGraph::decodeRoom), + decodeRows(root.get("roomExits"), "roomExits", WorldAuthoredGraph::decodeRoomExit), + decodeRows( + root.get("generationRules"), + "generationRules", + WorldAuthoredGraph::decodeGenerationRule), + decodeRows( + root.get("worldEntitySpawnBindings"), + "worldEntitySpawnBindings", + WorldAuthoredGraph::decodeSpawnBinding)); + if (!Arrays.equals(graph.encode(objectMapper), original)) { + throw malformed("World authored graph bytes are not in canonical encoding"); + } + return graph; + } + + private static List> decodeRows( + JsonNode rows, String family, Function> decoder) { + if (rows == null || !rows.isArray()) { + throw malformed("World authored graph family " + family + " is not an array"); + } + List> decodedRows = new ArrayList<>(rows.size()); + for (JsonNode row : rows) { + decodedRows.add(decoder.apply(row)); + } + return decodedRows; + } + + private static LinkedHashMap decodeRegion(JsonNode row) { + requireFields( + row, + "regions row", + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "regions row")); + decoded.put("shardId", nonNegativeInt(row, "shardId", "regions row")); + decoded.put("name", nonBlankString(row, "name", "regions row")); + decoded.put("weather", nullableString(row, "weather", "regions row")); + decoded.put("generationSeed", longValue(row, "generationSeed", "regions row")); + decoded.put("generatorType", nullableString(row, "generatorType", "regions row")); + decoded.put("generatorParams", nullableString(row, "generatorParams", "regions row")); + JsonNode spacing = row.get("spacingMultiplier"); + if (spacing == null || !spacing.isFloatingPointNumber()) { + throw malformed("World authored graph regions row spacingMultiplier is not a Double"); + } + double spacingValue = spacing.doubleValue(); + if (!Double.isFinite(spacingValue) || spacingValue <= 0.0d) { + throw malformed("World authored graph regions row spacingMultiplier is unsupported"); + } + decoded.put("spacingMultiplier", spacingValue); + return decoded; + } + + private static LinkedHashMap decodeZone(JsonNode row) { + requireFields(row, "zones row", "id", "regionId", "name"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "zones row")); + decoded.put("regionId", positiveLong(row, "regionId", "zones row")); + decoded.put("name", nonBlankString(row, "name", "zones row")); + return decoded; + } + + private static LinkedHashMap decodeRoom(JsonNode row) { + requireFields( + row, + "rooms row", + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "rooms row")); + decoded.put("zoneId", positiveLong(row, "zoneId", "rooms row")); + decoded.put("name", nonBlankString(row, "name", "rooms row")); + decoded.put("description", nullableString(row, "description", "rooms row")); + decoded.put( + "nameLocalizedVariantsJson", nullableString(row, "nameLocalizedVariantsJson", "rooms row")); + decoded.put( + "descriptionLocalizedVariantsJson", + nullableString(row, "descriptionLocalizedVariantsJson", "rooms row")); + return decoded; + } + + private static LinkedHashMap decodeRoomExit(JsonNode row) { + requireFields(row, "roomExits row", "id", "fromRoomId", "toRoomId", "direction", "cost"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "roomExits row")); + decoded.put("fromRoomId", positiveLong(row, "fromRoomId", "roomExits row")); + decoded.put("toRoomId", positiveLong(row, "toRoomId", "roomExits row")); + decoded.put("direction", nonBlankString(row, "direction", "roomExits row")); + decoded.put("cost", positiveInt(row, "cost", "roomExits row")); + return decoded; + } + + private static LinkedHashMap decodeGenerationRule(JsonNode row) { + requireFields(row, "generationRules row", "id", "name", "scopeType", "scopeId", "value"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "generationRules row")); + decoded.put("name", nonBlankString(row, "name", "generationRules row")); + String scopeType = nullableString(row, "scopeType", "generationRules row"); + String scopeId = nullableString(row, "scopeId", "generationRules row"); + if ((scopeType == null) != (scopeId == null)) { + throw malformed("World authored graph generationRules row has a partial scope"); + } + if (scopeType != null + && (!scopeType.equals("REGION_SUBTREE") && !scopeType.equals("ZONE_SUBTREE"))) { + throw malformed("World authored graph generationRules row scopeType is unsupported"); + } + if (scopeId != null) { + try { + long parsedScopeId = Long.parseLong(scopeId); + if (parsedScopeId <= 0L || !Long.toString(parsedScopeId).equals(scopeId)) { + throw malformed("World authored graph generationRules row scopeId is noncanonical"); + } + } catch (NumberFormatException exception) { + throw malformed( + "World authored graph generationRules row scopeId is unsupported", exception); + } + } + decoded.put("scopeType", scopeType); + decoded.put("scopeId", scopeId); + decoded.put("value", nullableString(row, "value", "generationRules row")); + return decoded; + } + + private static LinkedHashMap decodeSpawnBinding(JsonNode row) { + requireFields( + row, + "worldEntitySpawnBindings row", + "id", + "roomId", + "entityTemplateType", + "entityTemplateId", + "spawnCount", + "respawnDelaySeconds"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "worldEntitySpawnBindings row")); + decoded.put("roomId", positiveLong(row, "roomId", "worldEntitySpawnBindings row")); + String entityType = nonBlankString(row, "entityTemplateType", "worldEntitySpawnBindings row"); + if (!entityType.equals("ITEM") && !entityType.equals("NPC")) { + throw malformed("World authored graph worldEntitySpawnBindings row type is unsupported"); + } + decoded.put("entityTemplateType", entityType); + decoded.put( + "entityTemplateId", positiveLong(row, "entityTemplateId", "worldEntitySpawnBindings row")); + decoded.put("spawnCount", positiveInt(row, "spawnCount", "worldEntitySpawnBindings row")); + decoded.put( + "respawnDelaySeconds", + nonNegativeInt(row, "respawnDelaySeconds", "worldEntitySpawnBindings row")); + return decoded; + } + + private static void requireFields(JsonNode object, String label, String... fields) { + requireObject(object, label); + Set expected = Set.of(fields); + if (object.size() != expected.size()) { + throw malformed("World authored graph " + label + " has missing or extra fields"); + } + for (Map.Entry entry : object.properties()) { + if (!expected.contains(entry.getKey())) { + throw malformed("World authored graph " + label + " has an unknown field"); + } + } + for (String field : fields) { + if (object.get(field) == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + } + } + + private static void requireObject(JsonNode node, String label) { + if (node == null || !node.isObject()) { + throw malformed("World authored graph " + label + " is not an object"); + } + } + + private static long positiveLong(JsonNode object, String field, String label) { + long value = longValue(object, field, label); + if (value <= 0L) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static long longValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw malformed("World authored graph " + label + " " + field + " is not a Long"); + } + return value.longValue(); + } + + private static int positiveInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value <= 0) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static int nonNegativeInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value < 0) { + throw malformed("World authored graph " + label + " " + field + " is negative"); + } + return value; + } + + private static int intValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw malformed("World authored graph " + label + " " + field + " is not an Integer"); + } + return value.intValue(); + } + + private static String nonBlankString(JsonNode object, String field, String label) { + String value = stringValue(object, field, label, false); + if (value.isBlank()) { + throw malformed("World authored graph " + label + " " + field + " is blank"); + } + return value; + } + + private static String nullableString(JsonNode object, String field, String label) { + return stringValue(object, field, label, true); + } + + private static String stringValue(JsonNode object, String field, String label, boolean nullable) { + JsonNode value = object.get(field); + if (value == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + if (value.isNull() && nullable) { + return null; + } + if (!value.isString()) { + throw malformed("World authored graph " + label + " " + field + " is not a string"); + } + return value.stringValue(); + } + + private static SnapshotConflictException malformed(String message) { + return new SnapshotConflictException(message); + } + + private static SnapshotConflictException malformed(String message, Exception cause) { + SnapshotConflictException failure = new SnapshotConflictException(message); + failure.initCause(cause); + return failure; + } + WorldAuthoredGraph withRegions(List> updatedRegions) { return new WorldAuthoredGraph( updatedRegions, zones, rooms, roomExits, generationRules, spawnBindings); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java new file mode 100644 index 0000000000..3409cc3665 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; + +/** + * Shared internal six-family graph reader; callers must hold their exact owner transaction lock. + */ +final class WorldAuthoredGraphReader { + private static final Table REGION = table("region"); + private static final Table ZONE = table("zone"); + private static final Table ROOM = table("room"); + private static final Table ROOM_EXIT = table("room_exit"); + private static final Table GENERATION_RULE = table("generation_rule"); + private static final Table SPAWN_BINDING = table("world_entity_spawn_binding"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field REGION_ID = field("region_id", Long.class); + private static final Field ZONE_ID = field("zone_id", Long.class); + private static final Field FROM_ROOM_ID = field("from_room_id", Long.class); + private static final Field TO_ROOM_ID = field("to_room_id", Long.class); + private static final Field ROOM_ID = field("room_id", Long.class); + private static final Field GENERATION_SEED = field("generation_seed", Long.class); + private static final Field SHARD_ID = field("shard_id", Integer.class); + private static final Field NAME = field("name", String.class); + private static final Field WEATHER = field("weather", String.class); + private static final Field GENERATOR_TYPE = field("generator_type", String.class); + private static final Field GENERATOR_PARAMS = field("generator_params", String.class); + private static final Field SPACING_MULTIPLIER = field("spacing_multiplier", Double.class); + private static final Field DESCRIPTION = field("description", String.class); + private static final Field NAME_LOCALIZED_VARIANTS_JSON = + field("name_localized_variants_json", String.class); + private static final Field DESCRIPTION_LOCALIZED_VARIANTS_JSON = + field("description_localized_variants_json", String.class); + private static final Field DIRECTION = field("direction", String.class); + private static final Field COST = field("cost", Integer.class); + private static final Field SCOPE_TYPE = field("scope_type", String.class); + private static final Field SCOPE_ID = field("scope_id", String.class); + private static final Field RULE_VALUE = field("value", String.class); + private static final Field ENTITY_TEMPLATE_TYPE = + field("entity_template_type", String.class); + private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); + private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); + private static final Field RESPAWN_DELAY_SECONDS = + field("respawn_delay_seconds", Integer.class); + + private final DSLContext dsl; + + WorldAuthoredGraphReader(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { + List regionRows = fetch(REGION, tenantKey, versionKey); + List zoneRows = fetch(ZONE, tenantKey, versionKey); + List roomRows = fetch(ROOM, tenantKey, versionKey); + List exitRows = fetch(ROOM_EXIT, tenantKey, versionKey); + List ruleRows = fetch(GENERATION_RULE, tenantKey, versionKey); + List bindingRows = fetch(SPAWN_BINDING, tenantKey, versionKey); + + Map regionIds = new HashMap<>(); + Map zoneIds = new HashMap<>(); + Map roomIds = new HashMap<>(); + List> regions = new ArrayList<>(); + List> zones = new ArrayList<>(); + List> rooms = new ArrayList<>(); + List> exits = new ArrayList<>(); + List> rules = new ArrayList<>(); + List> bindings = new ArrayList<>(); + + for (Record row : regionRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "region.id"); + unique(regionIds, id, "region"); + Integer shard = required(row, SHARD_ID); + Long seed = required(row, GENERATION_SEED); + Double spacing = required(row, SPACING_MULTIPLIER); + String name = required(row, NAME); + if (shard < 0 || !Double.isFinite(spacing) || spacing <= 0.0d || name.isBlank()) { + throw incomplete("region", id, "unsupported required region data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("shardId", shard); + item.put("name", name); + item.put("weather", row.get(WEATHER, String.class)); + item.put("generationSeed", seed); + item.put("generatorType", row.get(GENERATOR_TYPE, String.class)); + item.put("generatorParams", row.get(GENERATOR_PARAMS, String.class)); + item.put("spacingMultiplier", spacing); + regions.add(item); + } + + for (Record row : zoneRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "zone.id"); + unique(zoneIds, id, "zone"); + long regionId = positive(row, REGION_ID, "zone.region_id"); + if (!regionIds.containsKey(regionId)) { + throw incomplete( + "zone", id, "region parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("zone", id, "zone name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("regionId", regionId); + item.put("name", name); + zones.add(item); + } + + for (Record row : roomRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room.id"); + unique(roomIds, id, "room"); + long zoneId = positive(row, ZONE_ID, "room.zone_id"); + if (!zoneIds.containsKey(zoneId)) { + throw incomplete("room", id, "zone parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("room", id, "room name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("zoneId", zoneId); + item.put("name", name); + item.put("description", row.get(DESCRIPTION, String.class)); + item.put("nameLocalizedVariantsJson", row.get(NAME_LOCALIZED_VARIANTS_JSON, String.class)); + item.put( + "descriptionLocalizedVariantsJson", + row.get(DESCRIPTION_LOCALIZED_VARIANTS_JSON, String.class)); + rooms.add(item); + } + + for (Record row : exitRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room_exit.id"); + long from = positive(row, FROM_ROOM_ID, "room_exit.from_room_id"); + long to = positive(row, TO_ROOM_ID, "room_exit.to_room_id"); + if (!roomIds.containsKey(from) || !roomIds.containsKey(to)) { + throw incomplete( + "room_exit", id, "exit endpoint is missing or belongs to another tenant/Version"); + } + String direction = required(row, DIRECTION); + Integer cost = required(row, COST); + if (direction.isBlank() || cost <= 0) { + throw incomplete("room_exit", id, "unsupported required room-exit data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("fromRoomId", from); + item.put("toRoomId", to); + item.put("direction", direction); + item.put("cost", cost); + exits.add(item); + } + + Set exactRuleKeys = new HashSet<>(); + Set unscopedRuleNames = new HashSet<>(); + for (Record row : ruleRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "generation_rule.id"); + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("generation_rule", id, "generation rule name is blank"); + } + String scopeType = row.get(SCOPE_TYPE, String.class); + String scopeId = row.get(SCOPE_ID, String.class); + if ((scopeType == null) != (scopeId == null)) { + throw incomplete( + "generation_rule", id, "scope_type and scope_id are only partially present"); + } + String stableScope; + if (scopeType == null) { + if (!unscopedRuleNames.add(name)) { + throw incomplete( + "generation_rule", id, "duplicate ambiguous unscoped generation rule name"); + } + stableScope = ""; + } else { + if (!"REGION_SUBTREE".equals(scopeType) && !"ZONE_SUBTREE".equals(scopeType)) { + throw incomplete("generation_rule", id, "unsupported generation rule scope type"); + } + long parsedScopeId = parseCanonicalPositiveId(scopeId, "generation_rule.scope_id", id); + if (("REGION_SUBTREE".equals(scopeType) && !regionIds.containsKey(parsedScopeId)) + || ("ZONE_SUBTREE".equals(scopeType) && !zoneIds.containsKey(parsedScopeId))) { + throw incomplete( + "generation_rule", id, "generation rule scope parent is missing or mismatched"); + } + stableScope = scopeType + ":" + scopeId; + } + if (!exactRuleKeys.add(stableScope + "\u0000" + name)) { + throw incomplete("generation_rule", id, "duplicate generation rule identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("name", name); + item.put("scopeType", scopeType); + item.put("scopeId", scopeId); + item.put("value", row.get(RULE_VALUE, String.class)); + rules.add(item); + } + + Set spawnKeys = new HashSet<>(); + for (Record row : bindingRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "world_entity_spawn_binding.id"); + long roomId = positive(row, ROOM_ID, "world_entity_spawn_binding.room_id"); + if (!roomIds.containsKey(roomId)) { + throw incomplete( + "world_entity_spawn_binding", + id, + "spawn room is missing or belongs to another tenant/Version"); + } + String entityType = required(row, ENTITY_TEMPLATE_TYPE); + Long entityId = required(row, ENTITY_TEMPLATE_ID); + Integer spawnCount = required(row, SPAWN_COUNT); + Integer delay = required(row, RESPAWN_DELAY_SECONDS); + if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) + || entityId <= 0L + || spawnCount <= 0 + || delay < 0) { + throw incomplete( + "world_entity_spawn_binding", id, "unsupported required spawn binding data"); + } + String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; + if (!spawnKeys.add(spawnKey)) { + throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("roomId", roomId); + item.put("entityTemplateType", entityType); + item.put("entityTemplateId", entityId); + item.put("spawnCount", spawnCount); + item.put("respawnDelaySeconds", delay); + bindings.add(item); + } + return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); + } + + private List fetch(Table table, long tenantKey, long versionKey) { + List fetchedRows = + dsl.selectFrom(table) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionKey))) + .orderBy(ID.asc()) + .fetch(); + List rows = new ArrayList<>(fetchedRows.size()); + rows.addAll(fetchedRows); + return rows; + } + + private void requireExactScope(Record row, long tenantKey, long versionKey) { + if (!Objects.equals(row.get(TENANT_ID, Long.class), tenantKey) + || !Objects.equals(row.get(VERSION_ID, Long.class), versionKey)) { + throw new SnapshotConflictException( + "World graph row returned outside the exact V27 tenant/Version scope"); + } + } + + private long positive(Record row, Field field, String label) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new SnapshotConflictException(label + " is missing or non-positive"); + } + return value; + } + + private long parseCanonicalPositiveId(String value, String label, long rowId) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new NumberFormatException("not canonical positive decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw incomplete("generation_rule", rowId, label + " is unsupported"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private SnapshotConflictException incomplete(String family, long id, String reason) { + return new SnapshotConflictException( + "World graph capture denied incomplete " + family + " row " + id + ": " + reason); + } + + private void unique(Map ids, long id, String family) { + if (ids.putIfAbsent(id, Boolean.TRUE) != null) { + throw incomplete(family, id, "duplicate row identity"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java index e253237762..2423f91209 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -5,13 +5,10 @@ import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import java.util.UUID; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; @@ -38,45 +35,11 @@ public class WorldAuthoredGraphSnapshotCapture { private static final int WORLD_DIGEST_SCHEMA_VERSION = 2; - private static final Table REGION = table("region"); - private static final Table ZONE = table("zone"); - private static final Table ROOM = table("room"); - private static final Table ROOM_EXIT = table("room_exit"); - private static final Table GENERATION_RULE = table("generation_rule"); - private static final Table SPAWN_BINDING = table("world_entity_spawn_binding"); private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); private static final Field ID = field("id", Long.class); private static final Field TENANT_ID = field("tenant_id", Long.class); private static final Field VERSION_ID = field("version_id", Long.class); - private static final Field REGION_ID = field("region_id", Long.class); - private static final Field ZONE_ID = field("zone_id", Long.class); - private static final Field FROM_ROOM_ID = field("from_room_id", Long.class); - private static final Field TO_ROOM_ID = field("to_room_id", Long.class); - private static final Field ROOM_ID = field("room_id", Long.class); - private static final Field GENERATION_SEED = field("generation_seed", Long.class); - private static final Field SHARD_ID = field("shard_id", Integer.class); - private static final Field NAME = field("name", String.class); - private static final Field WEATHER = field("weather", String.class); - private static final Field GENERATOR_TYPE = field("generator_type", String.class); - private static final Field GENERATOR_PARAMS = field("generator_params", String.class); - private static final Field SPACING_MULTIPLIER = field("spacing_multiplier", Double.class); - private static final Field DESCRIPTION = field("description", String.class); - private static final Field NAME_LOCALIZED_VARIANTS_JSON = - field("name_localized_variants_json", String.class); - private static final Field DESCRIPTION_LOCALIZED_VARIANTS_JSON = - field("description_localized_variants_json", String.class); - private static final Field DIRECTION = field("direction", String.class); - private static final Field COST = field("cost", Integer.class); - private static final Field SCOPE_TYPE = field("scope_type", String.class); - private static final Field SCOPE_ID = field("scope_id", String.class); - private static final Field RULE_VALUE = field("value", String.class); - private static final Field ENTITY_TEMPLATE_TYPE = - field("entity_template_type", String.class); - private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); - private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); - private static final Field RESPAWN_DELAY_SECONDS = - field("respawn_delay_seconds", Integer.class); private static final Field COMMIT_ID = field("commit_id", String.class); private static final Field REVISION_ID = field("revision_id", String.class); @@ -91,6 +54,7 @@ public class WorldAuthoredGraphSnapshotCapture { private static final Field SCOPE_EPOCH_AFTER = field("scope_epoch_after", Long.class); private final DSLContext dsl; + private final WorldAuthoredGraphReader graphReader; private final WorldDraftDesignDigestService draftDigestService; private final WorldAuthoredGraphSnapshotRepository snapshotRepository; private final ObjectMapper objectMapper; @@ -105,6 +69,7 @@ public WorldAuthoredGraphSnapshotCapture( WorldAuthoredGraphSnapshotRepository snapshotRepository, ObjectMapper objectMapper) { this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.graphReader = new WorldAuthoredGraphReader(dsl); this.draftDigestService = Objects.requireNonNull(draftDigestService, "draftDigestService must not be null"); this.snapshotRepository = @@ -140,7 +105,8 @@ public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { } String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); - WorldAuthoredGraph graph = readAndValidateGraph(provenance); + WorldAuthoredGraph graph = + graphReader.readAndValidateGraph(provenance.localTenantKey(), provenance.localVersionKey()); byte[] graphBytes = graph.encode(objectMapper); WorldDraftDesignDigest currentDigest = draftDigestService.getDraftDesignDigest( @@ -235,239 +201,6 @@ private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvena return writeJson(evidence); } - private WorldAuthoredGraph readAndValidateGraph(OwnerProvenance provenance) { - long tenantKey = provenance.localTenantKey(); - long versionKey = provenance.localVersionKey(); - List regionRows = fetch(REGION, tenantKey, versionKey); - List zoneRows = fetch(ZONE, tenantKey, versionKey); - List roomRows = fetch(ROOM, tenantKey, versionKey); - List exitRows = fetch(ROOM_EXIT, tenantKey, versionKey); - List ruleRows = fetch(GENERATION_RULE, tenantKey, versionKey); - List bindingRows = fetch(SPAWN_BINDING, tenantKey, versionKey); - - Map regionIds = new HashMap<>(); - Map zoneIds = new HashMap<>(); - Map roomIds = new HashMap<>(); - List> regions = new ArrayList<>(); - List> zones = new ArrayList<>(); - List> rooms = new ArrayList<>(); - List> exits = new ArrayList<>(); - List> rules = new ArrayList<>(); - List> bindings = new ArrayList<>(); - - for (Record row : regionRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "region.id"); - unique(regionIds, id, "region"); - Integer shard = required(row, SHARD_ID); - Long seed = required(row, GENERATION_SEED); - Double spacing = required(row, SPACING_MULTIPLIER); - String name = required(row, NAME); - if (shard < 0 || !Double.isFinite(spacing) || spacing <= 0.0d || name.isBlank()) { - throw incomplete("region", id, "unsupported required region data"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("shardId", shard); - item.put("name", name); - item.put("weather", row.get(WEATHER, String.class)); - item.put("generationSeed", seed); - item.put("generatorType", row.get(GENERATOR_TYPE, String.class)); - item.put("generatorParams", row.get(GENERATOR_PARAMS, String.class)); - item.put("spacingMultiplier", spacing); - regions.add(item); - } - - for (Record row : zoneRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "zone.id"); - unique(zoneIds, id, "zone"); - long regionId = positive(row, REGION_ID, "zone.region_id"); - if (!regionIds.containsKey(regionId)) { - throw incomplete( - "zone", id, "region parent is missing or belongs to another tenant/Version"); - } - String name = required(row, NAME); - if (name.isBlank()) { - throw incomplete("zone", id, "zone name is blank"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("regionId", regionId); - item.put("name", name); - zones.add(item); - } - - for (Record row : roomRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "room.id"); - unique(roomIds, id, "room"); - long zoneId = positive(row, ZONE_ID, "room.zone_id"); - if (!zoneIds.containsKey(zoneId)) { - throw incomplete("room", id, "zone parent is missing or belongs to another tenant/Version"); - } - String name = required(row, NAME); - if (name.isBlank()) { - throw incomplete("room", id, "room name is blank"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("zoneId", zoneId); - item.put("name", name); - item.put("description", row.get(DESCRIPTION, String.class)); - item.put("nameLocalizedVariantsJson", row.get(NAME_LOCALIZED_VARIANTS_JSON, String.class)); - item.put( - "descriptionLocalizedVariantsJson", - row.get(DESCRIPTION_LOCALIZED_VARIANTS_JSON, String.class)); - rooms.add(item); - } - - for (Record row : exitRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "room_exit.id"); - long from = positive(row, FROM_ROOM_ID, "room_exit.from_room_id"); - long to = positive(row, TO_ROOM_ID, "room_exit.to_room_id"); - if (!roomIds.containsKey(from) || !roomIds.containsKey(to)) { - throw incomplete( - "room_exit", id, "exit endpoint is missing or belongs to another tenant/Version"); - } - String direction = required(row, DIRECTION); - Integer cost = required(row, COST); - if (direction.isBlank() || cost <= 0) { - throw incomplete("room_exit", id, "unsupported required room-exit data"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("fromRoomId", from); - item.put("toRoomId", to); - item.put("direction", direction); - item.put("cost", cost); - exits.add(item); - } - - Set exactRuleKeys = new HashSet<>(); - Set unscopedRuleNames = new HashSet<>(); - for (Record row : ruleRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "generation_rule.id"); - String name = required(row, NAME); - if (name.isBlank()) { - throw incomplete("generation_rule", id, "generation rule name is blank"); - } - String scopeType = row.get(SCOPE_TYPE, String.class); - String scopeId = row.get(SCOPE_ID, String.class); - if ((scopeType == null) != (scopeId == null)) { - throw incomplete( - "generation_rule", id, "scope_type and scope_id are only partially present"); - } - String stableScope; - if (scopeType == null) { - if (!unscopedRuleNames.add(name)) { - throw incomplete( - "generation_rule", id, "duplicate ambiguous unscoped generation rule name"); - } - stableScope = ""; - } else { - if (!"REGION_SUBTREE".equals(scopeType) && !"ZONE_SUBTREE".equals(scopeType)) { - throw incomplete("generation_rule", id, "unsupported generation rule scope type"); - } - long parsedScopeId = parseCanonicalPositiveId(scopeId, "generation_rule.scope_id", id); - if (("REGION_SUBTREE".equals(scopeType) && !regionIds.containsKey(parsedScopeId)) - || ("ZONE_SUBTREE".equals(scopeType) && !zoneIds.containsKey(parsedScopeId))) { - throw incomplete( - "generation_rule", id, "generation rule scope parent is missing or mismatched"); - } - stableScope = scopeType + ":" + scopeId; - } - if (!exactRuleKeys.add(stableScope + "\u0000" + name)) { - throw incomplete("generation_rule", id, "duplicate generation rule identity"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("name", name); - item.put("scopeType", scopeType); - item.put("scopeId", scopeId); - item.put("value", row.get(RULE_VALUE, String.class)); - rules.add(item); - } - - Set spawnKeys = new HashSet<>(); - for (Record row : bindingRows) { - requireExactScope(row, tenantKey, versionKey); - long id = positive(row, ID, "world_entity_spawn_binding.id"); - long roomId = positive(row, ROOM_ID, "world_entity_spawn_binding.room_id"); - if (!roomIds.containsKey(roomId)) { - throw incomplete( - "world_entity_spawn_binding", - id, - "spawn room is missing or belongs to another tenant/Version"); - } - String entityType = required(row, ENTITY_TEMPLATE_TYPE); - Long entityId = required(row, ENTITY_TEMPLATE_ID); - Integer spawnCount = required(row, SPAWN_COUNT); - Integer delay = required(row, RESPAWN_DELAY_SECONDS); - if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) - || entityId <= 0L - || spawnCount <= 0 - || delay < 0) { - throw incomplete( - "world_entity_spawn_binding", id, "unsupported required spawn binding data"); - } - String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; - if (!spawnKeys.add(spawnKey)) { - throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); - } - LinkedHashMap item = new LinkedHashMap<>(); - item.put("id", id); - item.put("roomId", roomId); - item.put("entityTemplateType", entityType); - item.put("entityTemplateId", entityId); - item.put("spawnCount", spawnCount); - item.put("respawnDelaySeconds", delay); - bindings.add(item); - } - return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); - } - - private List fetch(Table table, long tenantKey, long versionKey) { - List fetchedRows = - dsl.selectFrom(table) - .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionKey))) - .orderBy(ID.asc()) - .fetch(); - List rows = new ArrayList<>(fetchedRows.size()); - rows.addAll(fetchedRows); - return rows; - } - - private void requireExactScope(Record row, long tenantKey, long versionKey) { - if (!Objects.equals(row.get(TENANT_ID, Long.class), tenantKey) - || !Objects.equals(row.get(VERSION_ID, Long.class), versionKey)) { - throw new SnapshotConflictException( - "World graph row returned outside the exact V27 tenant/Version scope"); - } - } - - private long positive(Record row, Field field, String label) { - Long value = row.get(field, Long.class); - if (value == null || value <= 0L) { - throw new SnapshotConflictException(label + " is missing or non-positive"); - } - return value; - } - - private long parseCanonicalPositiveId(String value, String label, long rowId) { - try { - long parsed = Long.parseLong(value); - if (parsed <= 0L || !Long.toString(parsed).equals(value)) { - throw new NumberFormatException("not canonical positive decimal"); - } - return parsed; - } catch (NumberFormatException exception) { - throw incomplete("generation_rule", rowId, label + " is unsupported"); - } - } - private String encodeTuples(List tuples) { List> values = new ArrayList<>(); for (OwnedAffectedTuple tuple : tuples) { @@ -537,17 +270,6 @@ private T required(Record row, Field field) { return value; } - private SnapshotConflictException incomplete(String family, long id, String reason) { - return new SnapshotConflictException( - "World graph capture denied incomplete " + family + " row " + id + ": " + reason); - } - - private void unique(Map ids, long id, String family) { - if (ids.putIfAbsent(id, Boolean.TRUE) != null) { - throw incomplete(family, id, "duplicate row identity"); - } - } - private void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException("World graph capture requires a caller-owned transaction"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index 259f85bb16..e2ddd3823c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -129,6 +129,19 @@ public WorldDesignPublicationFenceRepository( */ @Transactional(propagation = Propagation.MANDATORY) public void lockOpen(OwnerBinding binding) { + lockOpenAndResolve(binding); + } + + /** Exact retained source and private keys, available only after the OPEN owner lock is held. */ + record OpenOwner( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) { + long localTenantKey() { + return receipt.localTenantKey(); + } + } + + @Transactional(propagation = Propagation.MANDATORY) + OpenOwner lockOpenAndResolve(OwnerBinding binding) { requireWritableReadCommittedOwnerTransaction(); ResolvedVersion resolvedVersion = resolveVersion(binding); Record owner = createAndLockOwner(resolvedVersion); @@ -139,6 +152,7 @@ public void lockOpen(OwnerBinding binding) { if (owner.get(CURRENT_PUBLICATION_FENCE, UUID.class) != null) { throw new ConflictException("Open World version unexpectedly retains a publication fence"); } + return new OpenOwner(binding, resolvedVersion.receipt(), resolvedVersion.localVersionKey()); } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java new file mode 100644 index 0000000000..65d6160c34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager.UnverifiedStagedContent; +import org.jooq.DSLContext; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Explicitly unwired internal staging prerequisite over the actual source-qualified owner graph. + * This grants no write permission, APPLIED result, synchronized visibility, or publication proof. + */ +public class WorldDraftRegionStagingService { + private final WorldDesignPublicationFenceRepository fenceRepository; + private final WorldAuthoredGraphReader graphReader; + private final WorldDraftRegionGraphStager stager; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this internal component has no finalizer.") + public WorldDraftRegionStagingService( + DSLContext dsl, WorldDesignPublicationFenceRepository fenceRepository) { + this(fenceRepository, new WorldAuthoredGraphReader(dsl), new WorldDraftRegionGraphStager()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this internal component has no finalizer.") + WorldDraftRegionStagingService( + WorldDesignPublicationFenceRepository fenceRepository, + WorldAuthoredGraphReader graphReader, + WorldDraftRegionGraphStager stager) { + this.fenceRepository = Objects.requireNonNull(fenceRepository, "fenceRepository"); + this.graphReader = Objects.requireNonNull(graphReader, "graphReader"); + this.stager = Objects.requireNonNull(stager, "stager"); + } + + /** + * Reads all six families after exact intake/V27 resolution and the shared OPEN owner lock. The + * caller owns the writable READ COMMITTED transaction. Only the existing owner lock row may be + * created; staged content remains in memory. + */ + @Transactional(propagation = Propagation.MANDATORY) + public UnverifiedStagedContent stage(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + OpenOwner owner = fenceRepository.lockOpenAndResolve(plan.ownerBinding()); + TargetProof target = plan.binding().target(); + AuthoredWorldSourceEvidence source = owner.receipt().source(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !Objects.equals(target.sourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(target.sourceProvenanceKind(), source.provenanceKind())) { + throw new WorldDesignPublicationFenceRepository.ConflictException( + "World Draft commit source provenance differs from the exact retained intake"); + } + WorldAuthoredGraph prior = + graphReader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()); + return stager.stage(plan, prior); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java index 4db6ce6def..4e1abe5ac8 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -3,8 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; import java.nio.charset.StandardCharsets; import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -13,11 +16,15 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; @@ -40,6 +47,13 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager.UnverifiedStagedContent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionStagingService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -367,18 +381,303 @@ void canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup() { .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); } + @Test + void sourceQualifiedOpenStagingReadsAllSixFamiliesWithoutChangingDatabaseContent() { + Fixture fixture = fixture(false, false); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, ownerBinding(fixture), false); + List before = syntheticRetentionRowCounts(fixture); + UnverifiedStagedContent staged = + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan)); + + assertThat(staged.binding()).isSameAs(plan.binding()); + assertThat(staged.ownerBinding()).isSameAs(plan.ownerBinding()); + assertThat(fixture.localVersionKey()).isNotEqualTo(fixture.gameDesignVersionId()); + assertThat(fixture.intakeReceipt().localTenantKey()) + .isNotEqualTo(fixture.intakeReceipt().source().sourceGameRowId()); + assertThat(staged.graph().regions()).hasSize(2); + assertThat(staged.graph().regions().get(0)).containsEntry("name", "Staged region"); + assertThat(staged.graph().regions().get(1)).containsEntry("name", "Untouched region"); + assertThat(staged.graph().zones()).hasSize(1); + assertThat(staged.graph().rooms()) + .singleElement() + .satisfies(room -> assertThat(room).containsEntry("description", null)); + assertThat(staged.graph().roomExits()).hasSize(1); + assertThat(staged.graph().generationRules()).hasSize(1); + assertThat(staged.graph().spawnBindings()) + .singleElement() + .satisfies(binding -> assertThat(binding).containsEntry("entityTemplateId", LARGE_VALUE)); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND version_id = ?", + NAMESPACE, + fixture.request().canonicalTenantId(), + fixture.localVersionKey()), + "Staging must retain its exact OPEN owner row") + .get(0, String.class)) + .isEqualTo("OPEN"); + + // Both components must retain identical field/order/null/number encoding. This synthetic + // snapshot fixture proves representation equality, not synchronized owner application. + WorldAuthoredGraphSnapshot original = + ownerTransaction() + .execute(status -> captureComponent().capture(freezeOpenFixture(fixture))); + String expected = + new String(original.graphBytes(), StandardCharsets.UTF_8) + .replace("\"name\":\"authored region\"", "\"name\":\"Staged region\""); + assertThat(new String(staged.graph().encode(objectMapper), StandardCharsets.UTF_8)) + .isEqualTo(expected); + } + + @Test + void sourceQualifiedStagingRejectsChangedIntakeEvidenceBeforeOwnerCreation() { + Fixture fixture = fixture(false, false); + WorldDesignPublicationFenceEvidence.OwnerBinding exact = ownerBinding(fixture); + WorldDesignPublicationFenceEvidence.OwnerBinding changed = + new WorldDesignPublicationFenceEvidence.OwnerBinding( + exact.targetNamespace(), + exact.canonicalTenantId(), + exact.canonicalVersionId(), + exact.versionIdentityOperationId(), + exact.gameDesignVersionId(), + exact.intakeRequestId(), + exact.intakeOperationId(), + exact.intakeRequestDigest(), + exact.sourceOperationId(), + "sha256:" + "f".repeat(64), + exact.intakeReceiptDigest()); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, changed, false); + List before = syntheticRetentionRowCounts(fixture); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_fence_owner " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND version_id = ?", + NAMESPACE, + fixture.request().canonicalTenantId(), + fixture.localVersionKey()), + "PostgreSQL must return the owner row count") + .get(0, Long.class)) + .isZero(); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + } + + @Test + void sourceQualifiedStagingRejectsFrozenOwnerBeforeReadingAnInvalidPriorGraph() { + Fixture fixture = fixture(true); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, ownerBinding(fixture), false); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("not open"); + } + + @Test + void sourceQualifiedStagingRejectsCrossVersionParentAndLateInvalidRevisionWithoutAnyApply() { + Fixture invalidGraph = fixture(true, false); + WorldDraftRegionCommitPlan graphPlan = + stagingPlan(invalidGraph, ownerBinding(invalidGraph), false); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(graphPlan))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("zone parent"); + + Fixture fixture = fixture(false, false); + List before = syntheticRetentionRowCounts(fixture); + WorldDraftRegionCommitPlan lateInvalid = stagingPlan(fixture, ownerBinding(fixture), true); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(lateInvalid))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not exist"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT name FROM region WHERE tenant_id = ? AND version_id = ? AND id = ?", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + Long.parseLong( + fixture.request().suppliedOwnedAffectedTuples().get(0).aggregateId())), + "Rejected staging must retain the original region row") + .get(0, String.class)) + .isEqualTo("authored region"); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + private WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding(Fixture fixture) { + WorldAuthoredSourceIntakeReceipt intake = fixture.intakeReceipt(); + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + NAMESPACE, + intake.canonicalTenantId(), + fixture.request().canonicalVersionId(), + fixture.versionIdentityOperationId(), + fixture.gameDesignVersionId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest()); + } + + private WorldDraftRegionCommitPlan stagingPlan( + Fixture fixture, + WorldDesignPublicationFenceEvidence.OwnerBinding owner, + boolean lateInvalid) { + UUID commitId = UUID.randomUUID(); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + String regionId = fixture.request().suppliedOwnedAffectedTuples().get(0).aggregateId(); + List ids = + lateInvalid ? List.of(regionId, Long.toString(Long.MAX_VALUE)) : List.of(regionId); + for (String id : ids) { + UUID revisionId = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(id) + .setExpectedDraftRevisionEpoch(1L) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(id) + .setExpectedDraftScopeRevisionEpoch(1L) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Staged region") + .setGenerationSeed(LARGE_VALUE) + .setSpacingMultiplier(1.0d)) + .build(); + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(mutation))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + units.add(new AffectedUnit(Owner.WORLD_MANAGEMENT, "REGION", id, "AGGREGATE", id, "1")); + units.add(new AffectedUnit(Owner.WORLD_MANAGEMENT, "REGION", id, "REGION_SUBTREE", id, "1")); + } + AuthoredWorldSourceEvidence source = fixture.intakeReceipt().source(); + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.gameDesignVersionId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()), + UUID.randomUUID(), + commitId, + "synthetic-base", + revisions, + units); + return WorldDraftRegionCommitPlan.create(binding, owner); + } + + private CaptureRequest freezeOpenFixture(Fixture fixture) { + CaptureRequest request = fixture.request(); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = ownerBinding(fixture); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId()); + FrozenAttempt frozen = + publicationFenceRepository.claimFreeze( + evidence, + () -> + new Checkpoint( + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion())); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + frozen.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.suppliedOwnedAffectedTuples()); + } + private Fixture fixture(boolean wrongRoomParent) { + return fixture(wrongRoomParent, true); + } + + private Fixture fixture(boolean wrongRoomParent, boolean freeze) { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + // Synthetic authenticated-source prerequisite only. Persist the real intake in its own + // transaction, then read its committed result before any owner resolution or freeze. + AuthoredWorldSourceEvidence source = + source(canonicalTenantId, tenantSlug, worldSlug, positiveLong()); + UUID intakeRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequestId, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequestId).orElseThrow(); + assertThat(intake).isEqualTo(accepted); return ownerTransaction() .execute( status -> { - UUID canonicalTenantId = UUID.randomUUID(); - String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); - String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); - AuthoredWorldSourceEvidence source = - source(canonicalTenantId, tenantSlug, worldSlug, positiveLong()); - UUID intakeRequestId = UUID.randomUUID(); - WorldAuthoredSourceIntakeReceipt intake = - intakeRepository.acceptFresh(NAMESPACE, intakeRequestId, source); long gameDesignVersionId = GAME_DESIGN_VERSION_ID; UUID canonicalVersion = UUID.randomUUID(); UUID versionStateReadRequestId = UUID.randomUUID(); @@ -429,7 +728,7 @@ private Fixture fixture(boolean wrongRoomParent) { // canonical World owner producer exists or is proved by this fixture. SyntheticRows syntheticRows = seedSyntheticCanonicalRows( - intake.localTenantKey(), localVersionKey, wrongParentZoneId); + intake.localTenantKey(), localVersionKey, wrongParentZoneId, !freeze); assertGuardedSessionReplicationRole(); WorldDraftDesignDigest digest = draftDigestService.getDraftDesignDigest( @@ -461,15 +760,18 @@ private Fixture fixture(boolean wrongRoomParent) { REQUEST_DIGEST, versionStateEpoch, publishWorkflowId); - FrozenAttempt frozen = - publicationFenceRepository.claimFreeze( - fenceRequest, - () -> - new Checkpoint( - syntheticRows.commitId(), - digest.contentDigest(), - digest.digestSchemaVersion())); - UUID publicationFence = frozen.publicationFence(); + UUID publicationFence = + freeze + ? publicationFenceRepository + .claimFreeze( + fenceRequest, + () -> + new Checkpoint( + syntheticRows.commitId(), + digest.contentDigest(), + digest.digestSchemaVersion())) + .publicationFence() + : UUID.randomUUID(); CaptureRequest request = new CaptureRequest( NAMESPACE, @@ -513,7 +815,7 @@ private WorldAuthoredGraphSnapshot captureWithGuardedSessionRole( } private SyntheticRows seedSyntheticCanonicalRows( - long localTenantKey, long localVersionKey, Long wrongParentZoneId) { + long localTenantKey, long localVersionKey, Long wrongParentZoneId, boolean untouchedRegion) { String originalRole = currentSessionReplicationRole(); assertThat(originalRole).isEqualTo("origin"); Throwable seedFailure = null; @@ -532,6 +834,14 @@ private SyntheticRows seedSyntheticCanonicalRows( LARGE_VALUE) .fetchOne(0, Long.class), "Region insert did not return its generated ID"); + if (untouchedRegion) { + dsl.execute( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('Untouched region', ?, ?, ?)", + localTenantKey, + localVersionKey, + Long.MIN_VALUE); + } long zoneId = Objects.requireNonNull( dsl.resultQuery( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java index d9c3a198dd..279cd7ee30 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java @@ -1,4 +1,4 @@ -package unit.net.firedevops.firemud.worldmanagement.tenant; +package net.firedevops.firemud.worldmanagement.tenant; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -8,7 +8,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraph; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; @@ -130,6 +130,193 @@ void deeplyCopiesNestedRowsCollectionsAndByteArrays() { assertThatThrownBy(items::clear).isInstanceOf(UnsupportedOperationException.class); } + @Test + void decodesAndReencodesTheCanonicalSixFamilyGraphWithoutLosingNumericValues() { + ObjectMapper objectMapper = new ObjectMapper(); + byte[] encoded = completeGraph().encode(objectMapper); + + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(encoded, objectMapper); + + assertThat(decoded.encode(objectMapper)).containsExactly(encoded); + assertThat(decoded.regions()) + .extracting(row -> row.get("generationSeed")) + .containsExactly(Long.MIN_VALUE, Long.MAX_VALUE); + assertThat(decoded.regions().getFirst().get("id")).isEqualTo(Long.MAX_VALUE); + assertThat(decoded.regions().getFirst().get("spacingMultiplier")) + .isInstanceOf(Double.class) + .isEqualTo(0.125d); + assertThat(decoded.zones().getFirst().get("id")).isEqualTo(9_007_199_254_740_993L); + assertThat(decoded.rooms().getFirst().get("description")).isNull(); + assertThat(decoded.generationRules().getFirst().get("scopeId")).isNull(); + assertThat(decoded.spawnBindings().getFirst().get("entityTemplateId")) + .isEqualTo(9_007_199_254_740_999L); + } + + @Test + void rejectsMalformedRootFamiliesAndUnknownOrNoncanonicalSnapshots() { + ObjectMapper objectMapper = new ObjectMapper(); + String emptyGraph = + new String( + new WorldAuthoredGraph(List.of(), List.of(), List.of(), List.of(), List.of(), List.of()) + .encode(objectMapper), + StandardCharsets.UTF_8); + List invalidSnapshots = + List.of( + emptyGraph.replace("\"snapshotSchemaVersion\":1", "\"snapshotSchemaVersion\":2"), + emptyGraph.replace(",\"regions\":[]", ""), + emptyGraph.replace("\"zones\":[]", "\"unknown\":true,\"zones\":[]"), + emptyGraph.replace("\"regions\":[]", "\"regions\":{}"), + emptyGraph.replace("\"zones\":[]", "\"regions\":[],\"zones\":[]"), + " " + emptyGraph, + emptyGraph + " {}", + emptyGraph.replace(",\"zones\":[]", ",\"regions\":[],\"zones\":[]")); + + for (String invalidSnapshot : invalidSnapshots) { + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + assertThatThrownBy( + () -> WorldAuthoredGraph.decode(new byte[] {'{', '}', (byte) 0xc3, 0x28}, objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + + @Test + void rejectsMalformedRowsDuplicateFieldsAndChangedJsonTypes() { + ObjectMapper objectMapper = new ObjectMapper(); + String graph = new String(completeGraph().encode(objectMapper), StandardCharsets.UTF_8); + List invalidSnapshots = + List.of( + graph.replace("\"shardId\":4", "\"shardId\":\"4\""), + graph.replace("\"id\":9223372036854775807,", ""), + graph.replace( + "\"id\":9223372036854775807,", + "\"id\":9223372036854775807,\"id\":9223372036854775807,"), + graph.replace( + "\"id\":9223372036854775807,", "\"id\":9223372036854775807,\"unexpected\":0,"), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":\"0.125\""), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":0.1250"), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":1e9999"), + graph.replace( + "\"scopeType\":null,\"scopeId\":null", + "\"scopeType\":\"REGION_SUBTREE\",\"scopeId\":\"009\""), + graph.replace("\"shardId\":4,\"name\":\"edge\"", "\"name\":\"edge\",\"shardId\":4")); + + for (String invalidSnapshot : invalidSnapshots) { + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + } + + @Test + void decodedGraphDoesNotRetainMutableInputBytesAndExposesImmutableRows() { + ObjectMapper objectMapper = new ObjectMapper(); + byte[] input = completeGraph().encode(objectMapper); + byte[] canonical = input.clone(); + + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(input, objectMapper); + input[0] = 'x'; + + assertThat(decoded.encode(objectMapper)).containsExactly(canonical); + assertThatThrownBy(() -> decoded.regions().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> decoded.regions().getFirst().put("name", "changed")) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static WorldAuthoredGraph completeGraph() { + return new WorldAuthoredGraph( + List.of( + row( + "id", + Long.MAX_VALUE, + "shardId", + 4, + "name", + "edge", + "weather", + null, + "generationSeed", + Long.MIN_VALUE, + "generatorType", + null, + "generatorParams", + null, + "spacingMultiplier", + 0.125d), + row( + "id", + Long.MAX_VALUE - 1, + "shardId", + 0, + "name", + "edge-two", + "weather", + "clear", + "generationSeed", + Long.MAX_VALUE, + "generatorType", + "grid", + "generatorParams", + "{}", + "spacingMultiplier", + 3.75d)), + List.of( + row("id", 9_007_199_254_740_993L, "regionId", Long.MAX_VALUE, "name", "large-zone")), + List.of( + row( + "id", + 9_007_199_254_740_995L, + "zoneId", + 9_007_199_254_740_993L, + "name", + "large-room", + "description", + null, + "nameLocalizedVariantsJson", + "{}", + "descriptionLocalizedVariantsJson", + null)), + List.of( + row( + "id", + Long.MAX_VALUE - 2, + "fromRoomId", + 9_007_199_254_740_995L, + "toRoomId", + 9_007_199_254_740_995L, + "direction", + "east", + "cost", + 1)), + List.of( + row( + "id", Long.MAX_VALUE - 3, + "name", "unscoped-rule", + "scopeType", null, + "scopeId", null, + "value", null)), + List.of( + row( + "id", + Long.MAX_VALUE - 4, + "roomId", + 9_007_199_254_740_995L, + "entityTemplateType", + "ITEM", + "entityTemplateId", + 9_007_199_254_740_999L, + "spawnCount", + 1, + "respawnDelaySeconds", + 0))); + } + private static LinkedHashMap row(Object... values) { LinkedHashMap row = new LinkedHashMap<>(); for (int index = 0; index < values.length; index += 2) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java new file mode 100644 index 0000000000..f5581f163e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InOrder; + +class WorldDraftRegionStagingServiceTest { + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final WorldAuthoredGraphReader reader = mock(WorldAuthoredGraphReader.class); + private final WorldDraftRegionGraphStager stager = mock(WorldDraftRegionGraphStager.class); + private final WorldDraftRegionStagingService service = + new WorldDraftRegionStagingService(fence, reader, stager); + + @Test + void resolvesExactOwnerBeforeReadingServerPrivateKeysAndInvokingExistingStager() { + // Synthetic unit prerequisites: these doubles prove sequencing, not authenticated intake. + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + bindSyntheticSource(plan, receipt); + when(receipt.localTenantKey()).thenReturn(123L); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + WorldAuthoredGraph graph = + new WorldAuthoredGraph(List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + when(reader.readAndValidateGraph(123L, 456L)).thenReturn(graph); + WorldDraftRegionGraphStager.UnverifiedStagedContent content = + new WorldDraftRegionGraphStager.UnverifiedStagedContent(plan.binding(), binding, graph); + when(stager.stage(plan, graph)).thenReturn(content); + + assertThat(service.stage(plan)).isSameAs(content); + InOrder order = inOrder(fence, reader, stager); + order.verify(fence).lockOpenAndResolve(binding); + order.verify(reader).readAndValidateGraph(123L, 456L); + order.verify(stager).stage(plan, graph); + order.verifyNoMoreInteractions(); + assertThat(binding.gameDesignVersionId()).isNotEqualTo(456L); + } + + @Test + void rejectsClosedOwnerBeforeAnyGraphReadOrStaging() { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)) + .thenThrow(new WorldDesignPublicationFenceRepository.ConflictException("not OPEN")); + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + verifyNoInteractions(reader, stager); + } + + @Test + void incompletePriorGraphCannotReachStager() { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + bindSyntheticSource(plan, receipt); + when(receipt.localTenantKey()).thenReturn(123L); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + when(reader.readAndValidateGraph(123L, 456L)) + .thenThrow(new WorldAuthoredGraphSnapshotRepository.SnapshotConflictException("bad graph")); + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + verifyNoInteractions(stager); + } + + @ParameterizedTest + @ValueSource(strings = {"sourceGameRowId", "sourceGameTenantKey", "sourceProvenanceKind"}) + void rejectsEachChangedSourceFieldBeforeAnyGraphReadOrStaging(String changedField) { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + TargetProof target = bindSyntheticSource(plan, receipt); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + switch (changedField) { + case "sourceGameRowId" -> when(target.sourceGameRowId()).thenReturn(999L); + case "sourceGameTenantKey" -> + when(target.sourceGameTenantKey()).thenReturn("changed-source-key"); + case "sourceProvenanceKind" -> + when(target.sourceProvenanceKind()).thenReturn("changed-provenance"); + default -> throw new IllegalArgumentException("Unexpected synthetic negative field"); + } + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("source provenance"); + verifyNoInteractions(reader, stager); + } + + private static TargetProof bindSyntheticSource( + WorldDraftRegionCommitPlan plan, WorldAuthoredSourceIntakeReceipt receipt) { + // Complete compared provenance is stipulated here; these doubles do not prove authentication. + DraftCommitBinding binding = mock(DraftCommitBinding.class); + TargetProof target = mock(TargetProof.class); + AuthoredWorldSourceEvidence source = mock(AuthoredWorldSourceEvidence.class); + when(plan.binding()).thenReturn(binding); + when(binding.target()).thenReturn(target); + when(receipt.source()).thenReturn(source); + when(target.sourceGameRowId()).thenReturn(789L); + when(target.sourceGameTenantKey()).thenReturn("gd-row-789"); + when(target.sourceProvenanceKind()).thenReturn("NEW_GAME_ROW"); + when(source.sourceGameRowId()).thenReturn(789L); + when(source.sourceGameTenantKey()).thenReturn("gd-row-789"); + when(source.provenanceKind()).thenReturn("NEW_GAME_ROW"); + return target; + } + + private static OwnerBinding ownerBinding() { + return new OwnerBinding( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 987_654L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } +} From 19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:26:40 +1300 Subject: [PATCH 04/11] Order issuer and tenant source changes behind exact Draft outcomes --- .github/workflows/ci.yml | 32 + .../player-access-and-session.md | 6 +- .../world-runtime-and-movement.md | 2 +- .../DraftAuthorizationFenceBinding.java | 6 +- .../DraftAuthorizationFenceRepository.java | 5 + .../AccountIssuerAuthorityEventProducer.java | 73 ++- .../AccountTenantAuthorityEventProducer.java | 79 ++- ...suerTenantDraftSourceChangeRepository.java | 263 +++++++++ ...er_tenant_pending_draft_source_changes.sql | 192 ++++++ ...horityProducerPostgresIntegrationTest.java | 547 ++++++++++++++++++ ...horityProducerPostgresIntegrationTest.java | 433 ++++++++++++++ ...orizationFencePostgresIntegrationTest.java | 80 +++ .../DraftAuthorizationFenceBindingTest.java | 10 +- ...countIssuerAuthorityEventProducerTest.java | 11 + ...countTenantAuthorityEventProducerTest.java | 11 + ...dGraphSnapshotPostgresIntegrationTest.java | 18 +- 16 files changed, 1748 insertions(+), 20 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerTenantDraftSourceChangeRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V59__issuer_tenant_pending_draft_source_changes.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8a42d51f1..797af17588 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2127,6 +2127,8 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources()' \ account-service - name: Verify Game Design authored-draft publication PostgreSQL proof @@ -2373,8 +2375,38 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#transactionLocalEventReadbackFailureRollsBackTheAdvance()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#unavailablePostCommitReadDoesNotUndoAndExactRetryRecoversWithoutAdvancingAgain()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#generationAndSourceVersionOverflowFailBeforeAnyMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#issuerCommitOrderWaitsForEveryOriginalOwnerOutcomeBeforeAtomicSourceCompletion()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#issuerRevocationWaitsForBothExactAbortsAndPendingRequestAndCaptureAreImmutable()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#concurrentDistinctIssuerRequestsCannotLeaveCompetingPendingCaptures()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#sameRequestUuidAcrossExactIssuersHasDistinctPersistedSourceChangeIdentities()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#failedIssuerAdvanceRetainsOriginalPendingCaptureForExactRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEventBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParticipation()' \ account-service + - name: Verify Account tenant Draft source ordering PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#tenantCommitOrderWaitsForBothOriginalOwnerOutcomesBeforeAtomicSourceCompletion()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#tenantRevocationWaitsForExactAbortsAndKeepsOriginalPendingRequestAndCapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#concurrentDistinctTenantRequestsCannotLeaveCompetingPendingCaptures()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#sameRequestUuidAcrossEnrolledTenantsHasDistinctPersistedSourceChangeIdentities()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#failedTenantAdvanceRetainsOriginalPendingCaptureForExactRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#v59PreservesV58TenantAssociationCountersAndExactRetainedEventRetryWithoutBackfill()' \ + account-service + + - name: Upload Account tenant Draft source ordering PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-tenant-draft-source-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*TenantAuthorityProducerPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Verify Account issuer reconciliation capture PostgreSQL proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | 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 78943b17e7..a281b4318e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The current authored-publication candidate connects the explicitly unwired retained `EXPLICIT_JOIN` tenant-role writer to V57 source-change ordering. V58 permits only an immutable role request linked to the exact durable `WAITING` source intent to remain pending; pending results contain no audit, member result or authorization. Once both owner outcomes permit the source change, role, membership/pair counters, authority event, audit and source completion commit in the same Account transaction. Retry reads the original source vector instead of recapturing later state, and issuance-fence invalidation participates in both the membership and independently captured Account scopes. Four actual-writer ordering/recovery cases and two retained-journal/migration cases are defined; their corrected PostgreSQL execution remains required. The actor UUID is still a row selector, not authenticated caller proof, and creator bootstrap, hosted-terms sources and authenticated owner-result producers remain open. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) independently executed the nine existing authorization-fence PostgreSQL cases successfully with no skips and an Account job success; that checkpoint predates this source-writer integration and does not prove its new cases. +The current authored-publication candidate connects the explicitly unwired retained `EXPLICIT_JOIN` tenant-role writer to V57 source-change ordering. V58 permits only an immutable role request linked to the exact durable `WAITING` source intent to remain pending; pending results contain no audit, member result or authorization. Once both owner outcomes permit the source change, role, membership/pair counters, authority event, audit and source completion commit in the same Account transaction. Retry reads the original source vector instead of recapturing later state, and issuance-fence invalidation participates in both the membership and independently captured Account scopes. At source `9cf395d17398fe0b7fef8fae3a9e58d59e2ed949`, raw XML from [CI37326159559](https://github.com/benhook1013/FireMUD/actions/runs/37326159559) proves all 28 strict Account PostgreSQL selections passed without skips: nine existing authorization-fence cases and nineteen retained-role/journal cases, including the four source-writer ordering/recovery and two pending-journal/migration cases. The workflow-dispatch metadata pins the source; runner checkout was not independently verified. The actor UUID is still a row selector, not authenticated caller proof, and creator bootstrap, hosted-terms sources and authenticated owner-result producers remain open. + +The next candidate extends that ordering to the existing unwired issuer and tenant authority-event producers. V59 journals each exact `(source kind, scope, request UUID)` with one independently allocated source-change UUID, original request bytes and independently captured counters, checkpoint and event. An unresolved attempt commits only `WAITING` intent; actual source counters, outbox event, exact readback and both source-journal completions share the eventual Account transaction. A distinct overlapping pending source claim is denied before storing a competing stale capture, while exact retries and disjoint sources remain supported. V59 widens the exact source participation key without truncation or aliases and preserves V58 source/event history without backfill. Thirteen new producer and two shared-fence PostgreSQL cases are defined and required by CI; their execution remains unproved locally without Docker. This does not authenticate a caller, implement every Account-wide or hosted-terms source writer, enable an RPC, or complete the authoring fence. + +The corrected combined Account/World check, boot JAR, jOOQ schema generation, formatting, Checkstyle, SpotBugs, coverage and documentation gate passes. Parsed local unit results are Account 954 and World 256, all clean; the final gate reused those unchanged unit results from the preceding affected checks. All 381 Account and 65 World PostgreSQL methods compile but skip locally without Docker. Flyway sanity passes for twelve sets/190 files, and workflow/proof tooling and 230 architecture-contract tests pass. The narrow independent source/migration fix audit returned no new obligation; it is not broad corpus closure or authenticated producer proof. The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. Independently parsed raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for source `c5fd96e935028b72182d58a611152bee6a8e533b`, records all nine fence methods passing once without skips, errors or failures. Account's Gradle Checks passed, but the job was cancelled at post-Gradle setup; the observer could not retrieve checkout logs while the aggregate remained active, and Game Design and World proof failed separately. These are executed Account storage cases, not a green composed boundary or proof of an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. 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 3d68e3e02c..63e5a8470a 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The current publication candidate reuses one six-family database graph reader for both FROZEN capture and explicitly unwired OPEN region staging. OPEN staging resolves committed intake and V27 private keys under the existing owner lock, checks the enclosing commit's exact Game Design source provenance, and returns immutable unverified content without applying it or advancing synchronized visibility. Four database staging cases are defined; actual execution remains required. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) independently executed all eight publication-fence PostgreSQL cases successfully, while all four graph cases failed during fixture setup because independent committed intake readback ran before the intake transaction committed. The fixture now commits and reads back the real intake before owner resolution, preserving the canonical write guards and synthetic authentication prerequisites. Corrected execution remains open; staged representation and freeze storage still do not prove an authenticated owner apply, synchronized normal reads, release eligibility, fresh canonical content production or runtime topology materialization. +The current publication candidate reuses one six-family database graph reader for both FROZEN capture and explicitly unwired OPEN region staging. OPEN staging resolves committed intake and V27 private keys under the existing owner lock, checks the enclosing commit's exact Game Design source provenance, and returns immutable unverified content without applying it or advancing synchronized visibility. At source `9cf395d17398fe0b7fef8fae3a9e58d59e2ed949`, raw XML from [CI37326159559](https://github.com/benhook1013/FireMUD/actions/runs/37326159559) records all eight publication-fence PostgreSQL cases passing and all eight graph cases executing: two passed and six failed, with no skips. Four staging fixtures supplied a blank Game Design tenant key; two schema-denial assertions expected jOOQ exceptions instead of Spring's translated `DataIntegrityViolationException`. The fixtures now use the exact retained intake source key and check the actual translated exception plus SQLSTATE `23514` and the applicable owner constraint, preserving no-mutation assertions. Workflow-dispatch metadata pins the source; runner checkout was not independently verified. Corrected execution remains open; staged representation and freeze storage still do not prove an authenticated owner apply, synchronized normal reads, release eligibility, fresh canonical content production or runtime topology materialization. The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java index 410008700f..ea1e488fca 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java @@ -139,8 +139,10 @@ public record SourceEvidence( public SourceEvidence { Objects.requireNonNull(kind); text(scopeId); - if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 512) { - throw new IllegalArgumentException("Source participation key exceeds 512 UTF-8 bytes"); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); } if (kind == SourceKind.ACCOUNT || kind == SourceKind.TENANT diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index b69f547ae2..58ae2db252 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -224,6 +224,8 @@ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { /** * Commit this WAITING result even when false: rolling back would lose revocation intent. True * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. + * A distinct request overlapping an already pending source change is not admitted: it must not + * retain a second old-state capture that becomes stale when the first source change commits. */ public boolean requestSourceChange(SourceChange change) { requireTransaction(); @@ -235,6 +237,9 @@ public boolean requestSourceChange(SourceChange change) { return true; } } else { + if (hasWaitingChange(change.sources())) { + throw new IllegalStateException("Another authority source change is already pending"); + } dsl.execute( "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')", change.changeId(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java index 5eeca3130b..56eca9cb6c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java @@ -7,6 +7,8 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -44,6 +46,7 @@ public final class AccountIssuerAuthorityEventProducer { private final AccountAuthorityOutboxRepository outboxRepository; private final DSLContext dsl; private final TransactionTemplate ownerTransaction; + private final IssuerTenantDraftSourceChangeRepository draftSourceChanges; public AccountIssuerAuthorityEventProducer( String exactIssuerId, @@ -66,6 +69,7 @@ public AccountIssuerAuthorityEventProducer( Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); this.dsl = Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + this.draftSourceChanges = new IssuerTenantDraftSourceChangeRepository(dsl); this.ownerTransaction = new TransactionTemplate(transactionManager); this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -94,7 +98,7 @@ public IssuerGenerationAuthorityEvent advance( } requireNoAmbientTransaction(); - IssuerGenerationAuthorityEvent transactionResult = + AdvanceResult transactionResult = ownerTransaction.execute( status -> advanceInOwnerTransaction( @@ -102,10 +106,23 @@ public IssuerGenerationAuthorityEvent advance( if (transactionResult == null) { throw new IllegalStateException("Issuer authority advance transaction returned no event"); } + if (transactionResult.pendingChange() != null) { + ownerTransaction.executeWithoutResult( + status -> + draftSourceChanges.verifyWaiting( + SourceKind.ISSUER, + exactIssuerId, + requestId, + expectedIssuerAuthGeneration, + expectedSourceVersion, + transactionResult.pendingChange())); + throw new IssuerTenantDraftSourceChangeRepository.PendingSourceChangeException( + transactionResult.pendingChange().changeId()); + } IssuerGenerationAuthorityEvent committedResult = readCommittedOperation(requestId, expectedIssuerAuthGeneration, expectedSourceVersion); - if (!sameEvent(transactionResult, committedResult)) { + if (!sameEvent(transactionResult.event(), committedResult)) { throw new IllegalStateException( "Post-commit issuer event readback differs from its transaction result"); } @@ -176,7 +193,7 @@ IssuerAuthorityEventReadback readCommittedEventForProjectionReconciliation( return readCommittedEventInTransaction(outboxSequence); } - private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( + private AdvanceResult advanceInOwnerTransaction( UUID requestId, long expectedGeneration, long expectedSourceVersion) { ScopeState current = readLockedIssuerState(); @@ -188,9 +205,19 @@ private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( verifyStoredEvent(prior.get(), requestId, expectedGeneration, expectedSourceVersion); LatestEvidence currentHistory = requireCurrentHistoryMatches(current); requireHistoricalEventIsRetained(prior.get(), current, currentHistory); - return historical; + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.ISSUER, + exactIssuerId, + requestId, + expectedGeneration, + expectedSourceVersion, + prior.get()); + return new AdvanceResult(historical, null); } + draftSourceChanges.verifyPendingRequest( + SourceKind.ISSUER, exactIssuerId, requestId, expectedGeneration, expectedSourceVersion); + if (current.generation() != expectedGeneration || current.sourceVersion() != expectedSourceVersion) { throw new IllegalStateException("Issuer authority source compare-and-advance is stale"); @@ -200,6 +227,24 @@ private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( long nextSourceVersion = incrementExact(expectedSourceVersion, "issuer source version"); LatestEvidence priorHistory = requireCurrentHistoryMatches(current); long nextSequence = incrementExact(priorHistory.sequence(), "issuer outbox sequence"); + SourceChange sourceChange = + draftSourceChanges.participate( + SourceKind.ISSUER, + exactIssuerId, + requestId, + expectedGeneration, + expectedSourceVersion, + IssuerTenantDraftSourceChangeRepository.capture( + SourceKind.ISSUER, + exactIssuerId, + current.generation(), + current.sourceVersion(), + outboxStreamKey, + priorHistory.sequence(), + priorHistory.outboxEvent())); + if (!draftSourceChanges.permitted(sourceChange)) { + return new AdvanceResult(null, sourceChange); + } String requestText = requestId.toString(); String eventId = EVENT_ID_PREFIX + requestText; @@ -255,7 +300,16 @@ private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( throw new IllegalStateException( "Issuer authority source and outbox readback differ from the advance"); } - return appendedEvent; + draftSourceChanges.complete( + SourceKind.ISSUER, exactIssuerId, requestId, sourceChange, appended); + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.ISSUER, + exactIssuerId, + requestId, + expectedGeneration, + expectedSourceVersion, + appended); + return new AdvanceResult(appendedEvent, null); } private IssuerGenerationAuthorityEvent readCommittedOperation( @@ -277,6 +331,13 @@ private IssuerGenerationAuthorityEvent readCommittedOperation( committed, requestId, expectedGeneration, expectedSourceVersion); LatestEvidence currentHistory = requireCurrentHistoryMatches(current); requireHistoricalEventIsRetained(committed, current, currentHistory); + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.ISSUER, + exactIssuerId, + requestId, + expectedGeneration, + expectedSourceVersion, + committed); if (committed.outboxSequence() > currentHistory.sequence()) { throw new IllegalStateException( "Post-commit issuer event is ahead of its checkpoint"); @@ -349,6 +410,8 @@ private ScopeState readLockedIssuerState() { return state; } + private record AdvanceResult(IssuerGenerationAuthorityEvent event, SourceChange pendingChange) {} + /** * Validates the exact V33 checkpoint and latest event while the source row is locked. Sequence * zero is returned only after counting the exact stream's events and proving the original source diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java index aff7b619c8..f26ccf7bb9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java @@ -7,6 +7,8 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -42,6 +44,7 @@ public final class AccountTenantAuthorityEventProducer { private final AccountAuthorityOutboxRepository outboxRepository; private final DSLContext dsl; private final TransactionTemplate ownerTransaction; + private final IssuerTenantDraftSourceChangeRepository draftSourceChanges; public AccountTenantAuthorityEventProducer( AccountAuthorityGenerationRepository generationRepository, @@ -54,6 +57,7 @@ public AccountTenantAuthorityEventProducer( Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); this.dsl = Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + this.draftSourceChanges = new IssuerTenantDraftSourceChangeRepository(dsl); this.ownerTransaction = new TransactionTemplate(transactionManager); this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -78,7 +82,7 @@ public TenantGenerationAuthorityEvent advance( } requireNoAmbientTransaction(); - TenantGenerationAuthorityEvent transactionResult = + AdvanceResult transactionResult = ownerTransaction.execute( status -> advanceInOwnerTransaction( @@ -86,10 +90,23 @@ public TenantGenerationAuthorityEvent advance( if (transactionResult == null) { throw new IllegalStateException("Tenant authority advance transaction returned no event"); } + if (transactionResult.pendingChange() != null) { + ownerTransaction.executeWithoutResult( + status -> + draftSourceChanges.verifyWaiting( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion, + transactionResult.pendingChange())); + throw new IssuerTenantDraftSourceChangeRepository.PendingSourceChangeException( + transactionResult.pendingChange().changeId()); + } TenantGenerationAuthorityEvent committedResult = readCommittedOperation(scope, requestId, expectedGeneration, expectedSourceVersion); - if (!sameEvent(transactionResult, committedResult)) { + if (!sameEvent(transactionResult.event(), committedResult)) { throw new IllegalStateException( "Post-commit tenant event readback differs from its transaction result"); } @@ -131,7 +148,7 @@ public TenantAuthorityEventReadback readCommittedEvent(UUID tenantId, long outbo return readback; } - private TenantGenerationAuthorityEvent advanceInOwnerTransaction( + private AdvanceResult advanceInOwnerTransaction( AuthorityScope scope, UUID requestId, long expectedGeneration, long expectedSourceVersion) { ScopeState current = readLockedTenantState(scope); String streamKey = streamKey(scope); @@ -145,8 +162,22 @@ private TenantGenerationAuthorityEvent advanceInOwnerTransaction( prior.get(), scope, requestId, expectedGeneration, expectedSourceVersion); LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, current); requireHistoricalEventIsRetained(prior.get(), scope, current, currentHistory); - return historical; - } + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion, + prior.get()); + return new AdvanceResult(historical, null); + } + + draftSourceChanges.verifyPendingRequest( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion); if (current.generation() != expectedGeneration || current.sourceVersion() != expectedSourceVersion) { @@ -157,6 +188,24 @@ private TenantGenerationAuthorityEvent advanceInOwnerTransaction( long nextSourceVersion = incrementExact(expectedSourceVersion, "tenant source version"); LatestEvidence priorHistory = requireCurrentHistoryMatches(scope, current); long nextSequence = incrementExact(priorHistory.sequence(), "tenant outbox sequence"); + SourceChange sourceChange = + draftSourceChanges.participate( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion, + IssuerTenantDraftSourceChangeRepository.capture( + SourceKind.TENANT, + scope.tenantId().toString(), + current.generation(), + current.sourceVersion(), + streamKey, + priorHistory.sequence(), + priorHistory.outboxEvent())); + if (!draftSourceChanges.permitted(sourceChange)) { + return new AdvanceResult(null, sourceChange); + } String requestText = requestId.toString(); String eventId = EVENT_ID_PREFIX + requestText; @@ -213,7 +262,16 @@ private TenantGenerationAuthorityEvent advanceInOwnerTransaction( throw new IllegalStateException( "Tenant authority source and outbox readback differ from the advance"); } - return appendedEvent; + draftSourceChanges.complete( + SourceKind.TENANT, scope.tenantId().toString(), requestId, sourceChange, appended); + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion, + appended); + return new AdvanceResult(appendedEvent, null); } private TenantGenerationAuthorityEvent readCommittedOperation( @@ -236,6 +294,13 @@ private TenantGenerationAuthorityEvent readCommittedOperation( committed, scope, requestId, expectedGeneration, expectedSourceVersion); LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, current); requireHistoricalEventIsRetained(committed, scope, current, currentHistory); + draftSourceChanges.verifyCommittedIfPresent( + SourceKind.TENANT, + scope.tenantId().toString(), + requestId, + expectedGeneration, + expectedSourceVersion, + committed); if (committed.outboxSequence() > currentHistory.sequence()) { throw new IllegalStateException( "Post-commit tenant event is ahead of its checkpoint"); @@ -310,6 +375,8 @@ private ScopeState readLockedTenantState(AuthorityScope scope) { return state; } + private record AdvanceResult(TenantGenerationAuthorityEvent event, SourceChange pendingChange) {} + /** * Validates the exact stream checkpoint and latest event while the tenant source row is locked. * Sequence zero requires the original positive source baseline and proved absence of all event diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerTenantDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerTenantDraftSourceChangeRepository.java new file mode 100644 index 0000000000..da5de3bb54 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerTenantDraftSourceChangeRepository.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.IdempotencyConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** Unwired exact issuer/tenant request journal; callers retain their actual source row locks. */ +public final class IssuerTenantDraftSourceChangeRepository { + private static final String TABLE = "account_issuer_tenant_draft_source_changes"; + private static final String REQUEST_SCHEMA = "account-issuer-tenant-draft-source-request/v1"; + private final DSLContext dsl; + private final DraftAuthorizationFenceRepository fences; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The transaction-aware DSLContext is an internal persistence collaborator.") + public IssuerTenantDraftSourceChangeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + this.fences = new DraftAuthorizationFenceRepository(dsl); + } + + /** The source kind, exact scope and request UUID jointly identify an immutable request. */ + SourceChange participate( + SourceKind kind, + String scopeId, + UUID requestId, + long expectedGeneration, + long expectedVersion, + SourceEvidence current) { + byte[] request = requestBytes(kind, scopeId, requestId, expectedGeneration, expectedVersion); + Record prior = find(kind, scopeId, requestId); + SourceChange change; + if (prior != null) { + change = requireRequest(prior, request); + if (!"WAITING".equals(prior.get("status", String.class))) { + throw new IllegalStateException("Completed source request has no retained event"); + } + if (!Arrays.equals(change.sources().getFirst().canonicalBytes(), current.canonicalBytes())) { + throw new IllegalStateException("Pending source request differs from its original capture"); + } + } else { + change = new SourceChange(UUID.randomUUID(), List.of(current), request); + } + fences.requestSourceChange(change); + if (prior == null) { + dsl.execute( + "INSERT INTO " + + TABLE + + " (source_kind, scope_id, request_id, expected_generation, expected_source_version," + + " request_payload, source_change_id, source_evidence, source_change_binding, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING')", + kind.name(), + scopeId, + requestId, + expectedGeneration, + expectedVersion, + request, + change.changeId(), + current.canonicalBytes(), + change.canonicalBytes()); + } + requireRequest(find(kind, scopeId, requestId), request); + return change; + } + + /** Check original pending input before comparing against today's source state. */ + void verifyPendingRequest( + SourceKind kind, String scopeId, UUID requestId, long generation, long version) { + Record row = find(kind, scopeId, requestId); + if (row != null) { + requireRequest(row, requestBytes(kind, scopeId, requestId, generation, version)); + } + } + + boolean permitted(SourceChange change) { + return fences.sourceMutationPermitted(change); + } + + /** Source counters, outbox and both journal transitions share the caller's short transaction. */ + void complete(SourceKind kind, String scopeId, UUID requestId, SourceChange change, Event event) { + fences.markSourceCommitted(change); + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP," + + " event_stream = ?, event_sequence = ?, event_id = ?, event_digest = ?, event_payload = ?" + + " WHERE source_kind = ? AND scope_id = ? AND request_id = ?" + + " AND source_change_id = ? AND status = 'WAITING'", + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + kind.name(), + scopeId, + requestId, + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Source request did not complete exactly once"); + } + } + + /** Existing pre-V59 events remain historical evidence; they are never backfilled. */ + void verifyCommittedIfPresent( + SourceKind kind, String scopeId, UUID requestId, long generation, long version, Event event) { + Record row = find(kind, scopeId, requestId); + if (row == null) { + return; + } + SourceChange change = + requireRequest(row, requestBytes(kind, scopeId, requestId, generation, version)); + if (!"SOURCE_COMMITTED".equals(row.get("status", String.class)) + || !"SOURCE_COMMITTED".equals(fences.readSourceChange(change).status()) + || !event.outboxStreamKey().equals(row.get("event_stream", String.class)) + || !Long.valueOf(event.outboxSequence()).equals(row.get("event_sequence", Long.class)) + || !event.eventId().equals(row.get("event_id", String.class)) + || !event.eventDigest().equals(row.get("event_digest", String.class)) + || !Arrays.equals(event.payload(), row.get("event_payload", byte[].class))) { + throw new IllegalStateException("Source request and retained event linkage differ"); + } + } + + void verifyWaiting( + SourceKind kind, + String scopeId, + UUID requestId, + long generation, + long version, + SourceChange change) { + Record row = find(kind, scopeId, requestId); + SourceChange stored = + requireRequest(row, requestBytes(kind, scopeId, requestId, generation, version)); + if (!Arrays.equals(stored.canonicalBytes(), change.canonicalBytes()) + || !"WAITING".equals(row.get("status", String.class)) + || !"WAITING".equals(fences.readSourceChange(stored).status())) { + throw new IllegalStateException("Pending source request readback differs from its capture"); + } + } + + static SourceEvidence capture( + SourceKind kind, + String scopeId, + long generation, + long version, + String stream, + long sequence, + Optional latest) { + if ((sequence == 0) == latest.isPresent()) { + throw new IllegalStateException( + "Source checkpoint does not bind its verified latest evidence"); + } + ByteArrayOutputStream baseline = new ByteArrayOutputStream(); + if (sequence == 0) { + if (generation != 1 || version != 1) { + throw new IllegalStateException("Source baseline must already be proved positive 1/1"); + } + for (String field : + List.of( + "account-issuer-tenant-source-baseline/v1", + kind.name(), + scopeId, + "1", + "1", + stream, + "0")) { + frame(baseline, field); + } + } + return new SourceEvidence( + kind, + scopeId, + Long.toString(generation), + Long.toString(version), + stream, + Long.toString(sequence), + latest.map(Event::payload).orElseGet(baseline::toByteArray)); + } + + private Record find(SourceKind kind, String scopeId, UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE source_kind = ? AND scope_id = ? AND request_id = ? FOR UPDATE", + kind.name(), + scopeId, + requestId); + } + + private SourceChange requireRequest(Record row, byte[] request) { + if (row == null || !Arrays.equals(request, row.get("request_payload", byte[].class))) { + throw new IdempotencyConflictException( + "Source request identity was reused with different expected source state"); + } + SourceChange change = SourceChange.fromStored(row.get("source_change_binding", byte[].class)); + if (!change.changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals(change.mutation(), request) + || change.sources().size() != 1 + || !Arrays.equals( + change.sources().getFirst().canonicalBytes(), + row.get("source_evidence", byte[].class))) { + throw new IllegalStateException("Source journal differs from its immutable V57 capture"); + } + fences.readSourceChange(change); + return change; + } + + private static byte[] requestBytes( + SourceKind kind, String scopeId, UUID requestId, long generation, long version) { + if (kind != SourceKind.ISSUER && kind != SourceKind.TENANT) { + throw new IllegalArgumentException("Only issuer and tenant source writers participate here"); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + for (String field : + List.of( + REQUEST_SCHEMA, + kind.name(), + scopeId, + requestId.toString(), + Long.toString(generation), + Long.toString(version))) { + frame(bytes, field); + } + return bytes.toByteArray(); + } + + private static void frame(ByteArrayOutputStream output, String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + output.writeBytes(bytes); + } + + /** + * Deterministic nonterminal result, thrown only after the owner's WAITING transaction commits. + */ + public static final class PendingSourceChangeException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final UUID sourceChangeId; + + PendingSourceChangeException(UUID sourceChangeId) { + super("Draft owner outcomes remain pending for source change " + sourceChangeId); + this.sourceChangeId = sourceChangeId; + } + + public UUID sourceChangeId() { + return sourceChangeId; + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V59__issuer_tenant_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V59__issuer_tenant_pending_draft_source_changes.sql new file mode 100644 index 0000000000..38eb429554 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V59__issuer_tenant_pending_draft_source_changes.sql @@ -0,0 +1,192 @@ +-- Existing exact source identities and all V36..V58 history remain unchanged. Support the full +-- configured issuer length without truncating or replacing its UTF-8 participation key. +ALTER TABLE account_draft_authorization_source_locks ALTER COLUMN source_key TYPE VARCHAR(2048); +ALTER TABLE account_draft_authorization_sources ALTER COLUMN source_key TYPE VARCHAR(2048); +ALTER TABLE account_draft_authorization_changed_scopes ALTER COLUMN source_key TYPE VARCHAR(2048); + +-- [jooq ignore start] +DO $$ +DECLARE + capacity_guard TEXT; + guard_count INTEGER; +BEGIN + SELECT count(*), min(constraint_row.conname::text) INTO guard_count, capacity_guard + FROM pg_constraint constraint_row + JOIN pg_attribute attribute_row ON attribute_row.attrelid = constraint_row.conrelid + AND attribute_row.attnum = ANY(constraint_row.conkey) + WHERE constraint_row.conrelid = 'account_draft_authorization_source_locks'::regclass + AND constraint_row.contype = 'c' AND attribute_row.attname = 'source_key'; + IF guard_count <> 1 THEN + RAISE EXCEPTION 'Expected the single existing V57 source-key capacity guard'; + END IF; + EXECUTE format('ALTER TABLE account_draft_authorization_source_locks DROP CONSTRAINT %I', capacity_guard); +END; +$$; +-- [jooq ignore stop] +ALTER TABLE account_draft_authorization_source_locks + ADD CONSTRAINT account_draft_authorization_source_key_capacity + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048); + +CREATE TABLE account_issuer_tenant_draft_source_changes ( + source_kind VARCHAR(6) NOT NULL CHECK (source_kind IN ('ISSUER', 'TENANT')), + scope_id VARCHAR(512) NOT NULL CHECK (length(scope_id) > 0), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + source_change_id UUID NOT NULL UNIQUE REFERENCES account_draft_authorization_source_changes(change_id) + CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + event_stream VARCHAR(1024), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(256), + event_digest VARCHAR(128), + event_payload BYTEA, + PRIMARY KEY (source_kind, scope_id, request_id), + CHECK (octet_length(source_kind || ':' || scope_id) <= 2048), + CHECK (CASE WHEN source_kind = 'TENANT' THEN scope_id = lower(scope_id::uuid::text) + AND scope_id <> '00000000-0000-0000-0000-000000000000' ELSE true END), + CHECK ((status = 'WAITING' AND committed_at IS NULL AND event_stream IS NULL + AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL AND event_payload IS NULL) + OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL AND event_stream IS NOT NULL + AND event_sequence IS NOT NULL AND event_id IS NOT NULL AND event_digest IS NOT NULL + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_issuer_tenant_source_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_issuer_tenant_source_journal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_request BYTEA; + expected_change BYTEA; + expected_source_prefix BYTEA; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + OR NEW.source_kind IS DISTINCT FROM OLD.source_kind + OR NEW.scope_id IS DISTINCT FROM OLD.scope_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation + OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id + OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Issuer/tenant source request and original capture are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + RETURN NEW; + END IF; + IF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Issuer/tenant source request must begin with a WAITING intent' + USING ERRCODE = '23514'; + END IF; + expected_request := account_issuer_tenant_source_frame(convert_to('account-issuer-tenant-draft-source-request/v1', 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.source_kind, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.scope_id, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.request_id::text, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.expected_generation::text, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.expected_source_version::text, 'UTF8')); + expected_source_prefix := account_issuer_tenant_source_frame(convert_to('account-draft-source-evidence/v1', 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.source_kind, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.scope_id, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to('PRESENT', 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.expected_generation::text, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.expected_source_version::text, 'UTF8')); + expected_change := account_issuer_tenant_source_frame(convert_to('account-draft-source-change/v1', 'UTF8')) + || account_issuer_tenant_source_frame(convert_to(NEW.source_change_id::text, 'UTF8')) + || account_issuer_tenant_source_frame(convert_to('1', 'UTF8')) + || account_issuer_tenant_source_frame(NEW.source_evidence) + || account_issuer_tenant_source_frame(NEW.request_payload); + IF NEW.request_payload IS DISTINCT FROM expected_request + OR substring(NEW.source_evidence FROM 1 FOR octet_length(expected_source_prefix)) IS DISTINCT FROM expected_source_prefix + OR NEW.source_change_binding IS DISTINCT FROM expected_change + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id AND status = 'WAITING' + AND binding = expected_change) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id) <> 1 + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id AND source_key = NEW.source_kind || ':' || NEW.scope_id) THEN + RAISE EXCEPTION 'Issuer/tenant request must bind its exact original V57 source intent' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_issuer_tenant_source_link_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_issuer_tenant_draft_source_changes%ROWTYPE; + change_status TEXT; + change_binding BYTEA; + selected_change UUID; +BEGIN + IF TG_TABLE_NAME = 'account_issuer_tenant_draft_source_changes' THEN + selected_change := NEW.source_change_id; + ELSE + selected_change := NEW.change_id; + END IF; + SELECT * INTO journal FROM account_issuer_tenant_draft_source_changes + WHERE source_change_id = selected_change; + IF NOT FOUND THEN + RETURN NULL; -- Other V57 source owners and retained history remain untouched. + END IF; + SELECT status, binding INTO change_status, change_binding + FROM account_draft_authorization_source_changes WHERE change_id = selected_change; + IF change_status IS DISTINCT FROM journal.status + OR change_binding IS DISTINCT FROM journal.source_change_binding THEN + RAISE EXCEPTION 'Issuer/tenant journal and V57 source transition must commit atomically' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' AND ( + journal.event_stream IS DISTINCT FROM 'account:auth-authority:v1:' || lower(journal.source_kind) || '/' || journal.scope_id + OR journal.event_id IS DISTINCT FROM CASE journal.source_kind + WHEN 'ISSUER' THEN 'account-issuer-authority-event-v1:' ELSE 'account-tenant-generation-event-v1:' END || journal.request_id::text + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence + AND request_id = journal.request_id::text AND event_id = journal.event_id + AND event_digest = journal.event_digest AND payload = journal.event_payload)) THEN + RAISE EXCEPTION 'Issuer/tenant completed request lacks its exact retained source event' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'WAITING' AND EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = 'account:auth-authority:v1:' || lower(journal.source_kind) || '/' || journal.scope_id + AND request_id = journal.request_id::text) THEN + RAISE EXCEPTION 'A WAITING issuer/tenant request cannot publish its source event' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_issuer_tenant_source_request_guard + BEFORE INSERT OR UPDATE ON account_issuer_tenant_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_issuer_tenant_source_journal_guard(); +CREATE TRIGGER account_issuer_tenant_source_delete_guard + BEFORE DELETE ON account_issuer_tenant_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_issuer_tenant_source_truncate_guard + BEFORE TRUNCATE ON account_issuer_tenant_draft_source_changes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_issuer_tenant_source_complete_guard + AFTER INSERT OR UPDATE ON account_issuer_tenant_draft_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_issuer_tenant_source_link_guard(); +CREATE CONSTRAINT TRIGGER account_issuer_tenant_source_v57_link_guard + AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_issuer_tenant_source_link_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index 72e48dffa1..aa93caf953 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -15,14 +16,27 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.IssuerTenantDraftSourceChangeRepository.PendingSourceChangeException; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -47,6 +61,443 @@ class IssuerAuthorityProducerPostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void issuerCommitOrderWaitsForEveryOriginalOwnerOutcomeBeforeAtomicSourceCompletion() { + for (List outcomes : + List.of( + List.of(Outcome.COMMITTED, Outcome.COMMITTED), + List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED), + List.of(Outcome.DEFINITIVELY_ABORTED, Outcome.DEFINITIVELY_ABORTED))) { + Fixture fixture = newFixture(); + seedIssuer(fixture); + DraftAuthorizationFenceBinding binding = + issuerBinding(ISSUER_ID, "1", "1", "0", new byte[] {1}); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction( + fixture.transaction(), + () -> { + fences.reserve(binding); + fences.claimCommitOrder(binding); + return null; + }); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingIssuerChange(fixture, ISSUER_ID, request); + assertThat(original.changeId()).isNotEqualTo(request); + assertThat(original.sources().getFirst().kind()).isEqualTo(SourceKind.ISSUER); + assertThat(original.sources().getFirst().scopeId()).isEqualTo(ISSUER_ID); + recordOwner(fixture, binding, Owner.WORLD, outcomes.get(0)); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class) + .satisfies( + error -> + assertThat(((PendingSourceChangeException) error).sourceChangeId()) + .isEqualTo(original.changeId())); + assertThat(readAuthority(fixture).generation()).isEqualTo(1); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + recordOwner(fixture, binding, Owner.GAME_DESIGN, outcomes.get(1)); + IssuerGenerationAuthorityEvent event = fixture.producer().advance(ISSUER_ID, request, 1, 1); + assertThat(event.issuerAuthGeneration()).isEqualTo("2"); + assertThat( + transaction(fixture.transaction(), () -> fences.readSourceChange(original).status())) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request), + "Committed issuer source journal row is missing") + .get(0, String.class)) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + transaction( + fixture.transaction(), + () -> fences.readOwnerResult(binding, Owner.WORLD).orElseThrow().outcome())) + .isEqualTo(outcomes.get(0)); + } + } + + @Test + void issuerRevocationWaitsForBothExactAbortsAndPendingRequestAndCaptureAreImmutable() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + DraftAuthorizationFenceBinding binding = + issuerBinding(ISSUER_ID, "1", "1", "0", new byte[] {1}); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction(fixture.transaction(), () -> fences.reserve(binding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingIssuerChange(fixture, ISSUER_ID, request); + byte[] stored = original.canonicalBytes(); + assertThat(transaction(fixture.transaction(), () -> fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> transaction(fixture.transaction(), () -> fences.claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 2, 1)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 2)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_issuer_tenant_draft_source_changes SET expected_generation = 2 WHERE request_id = ?", + request)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(pendingIssuerChange(fixture, ISSUER_ID, request).canonicalBytes()) + .containsExactly(stored); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + fences.markSourceCommitted(original); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("must commit atomically"); + assertThat(fixture.producer().advance(ISSUER_ID, request, 1, 1).issuerAuthGeneration()) + .isEqualTo("2"); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void concurrentDistinctIssuerRequestsCannotLeaveCompetingPendingCaptures() throws Exception { + Fixture fixture = newFixture(); + seedIssuer(fixture); + DraftAuthorizationFenceBinding binding = + issuerBinding(ISSUER_ID, "1", "1", "0", new byte[] {1}); + transaction( + fixture.transaction(), + () -> new DraftAuthorizationFenceRepository(fixture.transactionDsl()).reserve(binding)); + UUID original = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, original, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> { + await(start); + assertThatThrownBy( + () -> fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1, 1)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(PendingSourceChangeException.class); + }); + Future second = + executor.submit( + () -> { + await(start); + assertThatThrownBy( + () -> fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1, 1)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(PendingSourceChangeException.class); + }); + start.countDown(); + first.get(20, TimeUnit.SECONDS); + second.get(20, TimeUnit.SECONDS); + } + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isEqualTo(1); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + fixture.producer().advance(ISSUER_ID, original, 1, 1); + assertThat( + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 2, 2).issuerAuthGeneration()) + .isEqualTo("3"); + } + + @Test + void sameRequestUuidAcrossExactIssuersHasDistinctPersistedSourceChangeIdentities() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + String otherIssuer = "https://other.example.test/issuer"; + transaction( + fixture.transaction(), + () -> { + fixture.generations().initializeIssuerIfAbsent(otherIssuer); + return null; + }); + UUID request = UUID.randomUUID(); + IssuerGenerationAuthorityEvent first = fixture.producer().advance(ISSUER_ID, request, 1, 1); + AccountIssuerAuthorityEventProducer other = + new AccountIssuerAuthorityEventProducer( + otherIssuer, + fixture.generations(), + fixture.outbox(), + fixture.transactionDsl(), + fixture.transactionManager()); + IssuerGenerationAuthorityEvent second = other.advance(otherIssuer, request, 1, 1); + assertThat(first.issuerId()).isEqualTo(ISSUER_ID); + assertThat(second.issuerId()).isEqualTo(otherIssuer); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT source_change_id FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request) + .getValues(0, UUID.class)) + .hasSize(2) + .doesNotHaveDuplicates() + .doesNotContain(request); + } + + @Test + void failedIssuerAdvanceRetainsOriginalPendingCaptureForExactRetry() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + DraftAuthorizationFenceBinding binding = + issuerBinding(ISSUER_ID, "1", "1", "0", new byte[] {1}); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction(fixture.transaction(), () -> fences.reserve(binding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingIssuerChange(fixture, ISSUER_ID, request); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events ADD CONSTRAINT reject_pending_issuer_retry CHECK (event_id NOT LIKE 'account-issuer-authority-event-v1:%')"); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 1, 1)) + .isInstanceOf(RuntimeException.class); + assertThat(pendingIssuerChange(fixture, ISSUER_ID, request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(transaction(fixture.transaction(), () -> fences.readSourceChange(original).status())) + .isEqualTo("WAITING"); + assertThat( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request), + "Pending issuer source journal row is missing after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + assertThat(readAuthority(fixture).generation()).isEqualTo(1); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events DROP CONSTRAINT reject_pending_issuer_retry"); + assertThat(fixture.producer().advance(ISSUER_ID, request, 1, 1).issuerAuthGeneration()) + .isEqualTo("2"); + } + + @Test + void issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEventBytes() { + Fixture fixture = newFixture(); + fixture + .setupDsl() + .execute( + "INSERT INTO account_authority_generations (scope_kind, issuer_id, generation, source_version) VALUES ('ISSUER', ?, 3, 7)", + ISSUER_ID); + transaction( + fixture.transaction(), + () -> { + fixture + .generations() + .advance(fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)), null); + appendSeedEvent(fixture, UUID.randomUUID(), 4, 8); + return null; + }); + Event latest = + transaction( + fixture.transaction(), () -> fixture.outbox().findEvent(STREAM_KEY, 1L).orElseThrow()); + DraftAuthorizationFenceBinding binding = + issuerBinding(ISSUER_ID, "4", "8", "1", latest.payload()); + transaction( + fixture.transaction(), + () -> new DraftAuthorizationFenceRepository(fixture.transactionDsl()).reserve(binding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, request, 4, 8)) + .isInstanceOf(PendingSourceChangeException.class); + SourceEvidence captured = pendingIssuerChange(fixture, ISSUER_ID, request).sources().getFirst(); + assertThat(captured.generation()).isEqualTo("4"); + assertThat(captured.sourceVersion()).isEqualTo("8"); + assertThat(captured.checkpointSequence()).isEqualTo("1"); + assertThat(captured.evidence()).containsExactly(latest.payload()); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + IssuerGenerationAuthorityEvent advanced = fixture.producer().advance(ISSUER_ID, request, 4, 8); + assertThat(advanced.issuerAuthGeneration()).isEqualTo("5"); + assertThat(advanced.sourceVersion()).isEqualTo("9"); + assertThat(advanced.outboxSequence()).isEqualTo("2"); + } + + @Test + void v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParticipation() { + Fixture fixture = newFixture("58"); + seedIssuer(fixture); + UUID oldRequest = UUID.randomUUID(); + transaction( + fixture.transaction(), + () -> { + fixture + .generations() + .advance(fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)), null); + appendSeedEvent(fixture, oldRequest, 2, 2); + return null; + }); + DraftAuthorizationFenceBinding oldBinding = + issuerBinding(ISSUER_ID, "2", "2", "1", new byte[] {7}); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction(fixture.transaction(), () -> fences.reserve(oldBinding)); + SourceChange oldChange = + new SourceChange(UUID.randomUUID(), oldBinding.sources(), new byte[] {9}); + transaction(fixture.transaction(), () -> fences.requestSourceChange(oldChange)); + String oldEvents = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_outbox_events ORDER BY outbox_stream_key, outbox_sequence") + .formatJSON(); + String oldSources = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_sources ORDER BY source_key, operation_id") + .formatJSON(); + String oldLocks = + fixture + .setupDsl() + .fetch("SELECT * FROM account_draft_authorization_source_locks ORDER BY source_key") + .formatJSON(); + String oldChanges = + fixture + .setupDsl() + .fetch("SELECT * FROM account_draft_authorization_source_changes ORDER BY change_id") + .formatJSON(); + String oldChangedScopes = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_changed_scopes ORDER BY source_key, change_id") + .formatJSON(); + DriverManagerDataSource dataSource = + (DriverManagerDataSource) + ((DataSourceTransactionManager) fixture.transactionManager()).getDataSource(); + String schema = + Objects.requireNonNull( + Objects.requireNonNull( + fixture.setupDsl().fetchOne("SELECT current_schema()"), + "Issuer migration fixture schema row is missing") + .get(0, String.class), + "Issuer migration fixture schema is missing"); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_outbox_events ORDER BY outbox_stream_key, outbox_sequence") + .formatJSON()) + .isEqualTo(oldEvents); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_sources ORDER BY source_key, operation_id") + .formatJSON()) + .isEqualTo(oldSources); + assertThat( + fixture + .setupDsl() + .fetch("SELECT * FROM account_draft_authorization_source_locks ORDER BY source_key") + .formatJSON()) + .isEqualTo(oldLocks); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes ORDER BY change_id") + .formatJSON()) + .isEqualTo(oldChanges); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_changed_scopes ORDER BY source_key, change_id") + .formatJSON()) + .isEqualTo(oldChangedScopes); + assertThat( + transaction(fixture.transaction(), () -> fences.readSourceChange(oldChange).binding())) + .containsExactly(oldChange.canonicalBytes()); + assertThat(fixture.producer().advance(ISSUER_ID, oldRequest, 1, 1).requestId()) + .isEqualTo(oldRequest.toString()); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isZero(); + String longIssuer = "界".repeat(512); + transaction( + fixture.transaction(), + () -> { + fixture.generations().initializeIssuerIfAbsent(longIssuer); + return null; + }); + AccountIssuerAuthorityEventProducer producer = + new AccountIssuerAuthorityEventProducer( + longIssuer, + fixture.generations(), + fixture.outbox(), + fixture.transactionDsl(), + fixture.transactionManager()); + DraftAuthorizationFenceBinding longBinding = + issuerBinding(longIssuer, "1", "1", "0", new byte[] {1}); + transaction(fixture.transaction(), () -> fences.reserve(longBinding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> producer.advance(longIssuer, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + assertThat(pendingIssuerChange(fixture, longIssuer, request).sources().getFirst().scopeId()) + .isEqualTo(longIssuer); + recordOwner(fixture, longBinding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, longBinding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(producer.advance(longIssuer, request, 1, 1).issuerId()).isEqualTo(longIssuer); + assertThat( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ?", + "ISSUER:" + longIssuer), + "Exact multibyte issuer participation key row is missing") + .get(0, String.class)) + .isEqualTo("ISSUER:" + longIssuer); + } + @Test void atomicallyAdvancesSourceAndEventAndReadsBackExactCheckpoint() { Fixture fixture = newFixture(); @@ -454,6 +905,12 @@ void appendFailureRollsBackSourceAndOutboxTogether() { assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(1L); assertThat(countEvents(fixture, STREAM_KEY)).isZero(); assertThat(countStreams(fixture)).isZero(); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isZero(); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); } @Test @@ -552,6 +1009,10 @@ private IssuerGenerationAuthorityEvent concurrentAdvance( } private Fixture newFixture() { + return newFixture("latest"); + } + + private Fixture newFixture(String target) { String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; @@ -564,6 +1025,7 @@ private Fixture newFixture() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target(target) .load() .migrate(); @@ -579,6 +1041,91 @@ private Fixture newFixture() { setupDsl, transactionDsl, transactionManager, transaction, generations, outbox); } + private SourceChange pendingIssuerChange(Fixture fixture, String issuer, UUID request) { + byte[] binding = + Objects.requireNonNull( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT source_change_binding FROM account_issuer_tenant_draft_source_changes WHERE source_kind = 'ISSUER' AND scope_id = ? AND request_id = ?", + issuer, + request), + "Pending issuer source journal row is missing") + .get(0, byte[].class), + "Pending issuer source capture is missing"); + return SourceChange.fromStored(binding); + } + + private DraftAuthorizationFenceBinding issuerBinding( + String issuer, String generation, String version, String sequence, byte[] evidence) { + UUID tenant = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + tenant, UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "world-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "1"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + tenant, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ISSUER, + issuer, + generation, + version, + "account:auth-authority:v1:issuer/" + issuer, + sequence, + evidence))); + } + + private void recordOwner( + Fixture fixture, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + transaction( + fixture.transaction(), + () -> { + new DraftAuthorizationFenceRepository(fixture.transactionDsl()) + .recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1})); + return null; + }); + } + private void seedIssuer(Fixture fixture) { transaction( fixture.transaction(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java index 97a653e14c..3ddbf75fb4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -15,6 +16,14 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -22,8 +31,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.IssuerTenantDraftSourceChangeRepository.PendingSourceChangeException; import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -56,6 +70,331 @@ class TenantAuthorityProducerPostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void tenantCommitOrderWaitsForBothOriginalOwnerOutcomesBeforeAtomicSourceCompletion() { + for (List outcomes : + List.of( + List.of(Outcome.COMMITTED, Outcome.COMMITTED), + List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED), + List.of(Outcome.DEFINITIVELY_ABORTED, Outcome.DEFINITIVELY_ABORTED))) { + Fixture fixture = newFixture(); + seed(fixture); + DraftAuthorizationFenceBinding binding = tenantBinding(fixture); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction( + fixture.transaction(), + () -> { + fences.reserve(binding); + fences.claimCommitOrder(binding); + return null; + }); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingTenantChange(fixture, request); + assertThat(original.changeId()).isNotEqualTo(request); + SourceEvidence source = original.sources().getFirst(); + assertThat(source.kind()).isEqualTo(SourceKind.TENANT); + assertThat(source.scopeId()).isEqualTo(TENANT_ID.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.checkpointSequence()).isEqualTo("0"); + recordOwner(fixture, binding, Owner.WORLD, outcomes.get(0)); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class) + .satisfies( + error -> + assertThat(((PendingSourceChangeException) error).sourceChangeId()) + .isEqualTo(original.changeId())); + assertThat(readTenantState(fixture).generation()).isEqualTo(1); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + recordOwner(fixture, binding, Owner.GAME_DESIGN, outcomes.get(1)); + assertThat(fixture.producer().advance(TENANT_ID, request, 1, 1).tenantAuthorityGeneration()) + .isEqualTo("2"); + assertThat( + transaction(fixture.transaction(), () -> fences.readSourceChange(original).status())) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + transaction( + fixture.transaction(), + () -> fences.readOwnerResult(binding, Owner.WORLD).orElseThrow().outcome())) + .isEqualTo(outcomes.get(0)); + } + } + + @Test + void tenantRevocationWaitsForExactAbortsAndKeepsOriginalPendingRequestAndCapture() { + Fixture fixture = newFixture(); + seed(fixture); + ScopeState accountBefore = readAccountState(fixture); + DraftAuthorizationFenceBinding binding = tenantBinding(fixture); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction(fixture.transaction(), () -> fences.reserve(binding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingTenantChange(fixture, request); + byte[] stored = original.canonicalBytes(); + assertThat(transaction(fixture.transaction(), () -> fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> transaction(fixture.transaction(), () -> fences.claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 2, 1)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 2)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_issuer_tenant_draft_source_changes SET source_change_binding = ? WHERE request_id = ?", + new byte[] {2}, + request)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(pendingTenantChange(fixture, request).canonicalBytes()).containsExactly(stored); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + fences.markSourceCommitted(original); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("must commit atomically"); + fixture.producer().advance(TENANT_ID, request, 1, 1); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_issuer_tenant_draft_source_changes SET event_payload = ? WHERE request_id = ?", + new byte[] {3}, + request)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(readAccountState(fixture)).isEqualTo(accountBefore); + } + + @Test + void concurrentDistinctTenantRequestsCannotLeaveCompetingPendingCaptures() throws Exception { + Fixture fixture = newFixture(); + seed(fixture); + DraftAuthorizationFenceBinding binding = tenantBinding(fixture); + transaction( + fixture.transaction(), + () -> new DraftAuthorizationFenceRepository(fixture.transactionDsl()).reserve(binding)); + UUID original = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, original, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> { + await(start); + assertThatThrownBy( + () -> fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 1, 1)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(PendingSourceChangeException.class); + }); + Future second = + executor.submit( + () -> { + await(start); + assertThatThrownBy( + () -> fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 1, 1)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(PendingSourceChangeException.class); + }); + start.countDown(); + first.get(20, TimeUnit.SECONDS); + second.get(20, TimeUnit.SECONDS); + } + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isEqualTo(1); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + fixture.producer().advance(TENANT_ID, original, 1, 1); + assertThat( + fixture + .producer() + .advance(TENANT_ID, UUID.randomUUID(), 2, 2) + .tenantAuthorityGeneration()) + .isEqualTo("3"); + } + + @Test + void sameRequestUuidAcrossEnrolledTenantsHasDistinctPersistedSourceChangeIdentities() { + Fixture fixture = newFixture(); + seed(fixture); + FreshTenantCreationEvidence other = + tenantEvidence( + UUID.randomUUID(), UUID.randomUUID(), UNKNOWN_TENANT_ID, 732, "tenant-second"); + transaction( + fixture.transaction(), + () -> { + fixture.associations().importVerified(other); + fixture.generations().initializeTenantIfAbsent(UNKNOWN_TENANT_ID); + return null; + }); + UUID request = UUID.randomUUID(); + TenantGenerationAuthorityEvent first = fixture.producer().advance(TENANT_ID, request, 1, 1); + TenantGenerationAuthorityEvent second = + fixture.producer().advance(UNKNOWN_TENANT_ID, request, 1, 1); + assertThat(first.tenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(second.tenantId()).isEqualTo(UNKNOWN_TENANT_ID.toString()); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT source_change_id FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request) + .getValues(0, UUID.class)) + .hasSize(2) + .doesNotHaveDuplicates() + .doesNotContain(request); + } + + @Test + void failedTenantAdvanceRetainsOriginalPendingCaptureForExactRetry() { + Fixture fixture = newFixture(); + seed(fixture); + DraftAuthorizationFenceBinding binding = tenantBinding(fixture); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + transaction(fixture.transaction(), () -> fences.reserve(binding)); + UUID request = UUID.randomUUID(); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange original = pendingTenantChange(fixture, request); + recordOwner(fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events ADD CONSTRAINT reject_pending_tenant_retry CHECK (event_id NOT LIKE 'account-tenant-generation-event-v1:%')"); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, request, 1, 1)) + .isInstanceOf(RuntimeException.class); + assertThat(pendingTenantChange(fixture, request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(transaction(fixture.transaction(), () -> fences.readSourceChange(original).status())) + .isEqualTo("WAITING"); + assertThat( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + request), + "Pending tenant source journal row is missing after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + assertThat(readTenantState(fixture).generation()).isEqualTo(1); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events DROP CONSTRAINT reject_pending_tenant_retry"); + assertThat(fixture.producer().advance(TENANT_ID, request, 1, 1).tenantAuthorityGeneration()) + .isEqualTo("2"); + } + + @Test + void v59PreservesV58TenantAssociationCountersAndExactRetainedEventRetryWithoutBackfill() { + Fixture fixture = newFixture("58"); + seed(fixture); + UUID original = UUID.randomUUID(); + transaction( + fixture.transaction(), + () -> { + fixture + .generations() + .advance(fixture.generations().read(AuthorityScope.tenant(TENANT_ID)), null); + appendSeedEvent(fixture, original, 2, 2); + return null; + }); + String associations = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_fresh_tenant_identity_associations ORDER BY canonical_tenant_id") + .formatJSON(); + String generations = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_generations ORDER BY scope_kind, issuer_id, account_uuid, tenant_uuid") + .formatJSON(); + String events = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_outbox_events ORDER BY outbox_stream_key, outbox_sequence") + .formatJSON(); + DriverManagerDataSource dataSource = + (DriverManagerDataSource) + ((DataSourceTransactionManager) fixture.transactionManager()).getDataSource(); + String schema = + Objects.requireNonNull( + Objects.requireNonNull( + fixture.setupDsl().fetchOne("SELECT current_schema()"), + "Tenant migration fixture schema row is missing") + .get(0, String.class), + "Tenant migration fixture schema is missing"); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_fresh_tenant_identity_associations ORDER BY canonical_tenant_id") + .formatJSON()) + .isEqualTo(associations); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_generations ORDER BY scope_kind, issuer_id, account_uuid, tenant_uuid") + .formatJSON()) + .isEqualTo(generations); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_authority_outbox_events ORDER BY outbox_stream_key, outbox_sequence") + .formatJSON()) + .isEqualTo(events); + assertThat(fixture.producer().advance(TENANT_ID, original, 1, 1).requestId()) + .isEqualTo(original.toString()); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isZero(); + fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 2, 2); + assertThat(fixture.producer().advance(TENANT_ID, original, 1, 1).requestId()) + .isEqualTo(original.toString()); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isEqualTo(1); + } + @Test void atomicallyAdvancesEnrolledTenantSourceAndReadsBackExactCheckpointWithoutAccountFenceChange() { @@ -541,6 +880,12 @@ void appendFailureRollsBackTenantSourceAndOutboxTogether() { assertTenantCountersAndOutbox(fixture, 1L, 1L, 0L, 0L); assertThat(readAccountState(fixture)).isEqualTo(accountBefore); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_issuer_tenant_draft_source_changes"))) + .isZero(); + assertThat( + fixture.setupDsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); } @Test @@ -606,6 +951,10 @@ private TenantGenerationAuthorityEvent concurrentAdvance( } private Fixture newFixture() { + return newFixture("latest"); + } + + private Fixture newFixture(String target) { String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; @@ -618,6 +967,7 @@ private Fixture newFixture() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target(target) .load() .migrate(); @@ -672,6 +1022,89 @@ private void seed(Fixture fixture) { }); } + private SourceChange pendingTenantChange(Fixture fixture, UUID request) { + byte[] binding = + Objects.requireNonNull( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT source_change_binding FROM account_issuer_tenant_draft_source_changes WHERE source_kind = 'TENANT' AND scope_id = ? AND request_id = ?", + TENANT_ID.toString(), + request), + "Pending tenant source journal row is missing") + .get(0, byte[].class), + "Pending tenant source capture is missing"); + return SourceChange.fromStored(binding); + } + + private DraftAuthorizationFenceBinding tenantBinding(Fixture fixture) { + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + TENANT_ID, UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "world-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "1"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + fixture.accountUuid(), + TENANT_ID, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.TENANT, + TENANT_ID.toString(), + "1", + "1", + STREAM_KEY, + "0", + new byte[] {1}))); + } + + private void recordOwner( + Fixture fixture, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + transaction( + fixture.transaction(), + () -> { + new DraftAuthorizationFenceRepository(fixture.transactionDsl()) + .recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1})); + return null; + }); + } + private FreshTenantCreationEvidence tenantEvidence( UUID requestId, UUID operationId, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index 5cab281b91..c1e9720f24 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -347,6 +347,86 @@ void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflic .isEqualTo(Ordering.COMMIT_ORDER); } + @Test + void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var original = tx(context, () -> context.repository().readSourceChange(first)); + + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var exactRetry = tx(context, () -> context.repository().readSourceChange(first)); + assertThat(exactRetry.binding()).containsExactly(original.binding()); + assertThat(exactRetry.requestedAt()).isEqualTo(original.requestedAt()); + + // This storage fixture stipulates definitive owner evidence; it does not authenticate it. + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + tx( + context, + () -> { + context.repository().markSourceCommitted(first); + return null; + }); + assertThat(tx(context, () -> context.repository().requestSourceChange(second))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources() + throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var firstTask = + executor.submit( + () -> + tx( + context, + () -> { + boolean permitted = context.repository().requestSourceChange(first); + firstClaimed.countDown(); + await(secondStarted); + return permitted; + })); + var secondTask = + executor.submit( + () -> { + await(firstClaimed); + secondStarted.countDown(); + assertThatThrownBy( + () -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + }); + assertThat(firstTask.get(15, TimeUnit.SECONDS)).isFalse(); + secondTask.get(15, TimeUnit.SECONDS); + } + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + SourceChange disjoint = change(binding()); + assertThat(tx(context, () -> context.repository().requestSourceChange(disjoint))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + @Test void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { for (boolean commitWins : List.of(true, false)) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java index bf61abf915..14f50b6fd9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java @@ -169,16 +169,22 @@ void nonexistentCounterApplicabilityIsNotManufacturedForGlobalRoleBirth() { @Test void rejectsOversizedMultibyteParticipationKeyWithoutChangingCanonicalScopes() { - String exactLimit = "界".repeat(168) + "x"; + String exactLimit = "界".repeat(680) + "x"; SourceEvidence retained = new SourceEvidence(SourceKind.ISSUER, exactLimit, "1", "1", "stream", "0", new byte[] {1}); assertThat(retained.scopeId()).isEqualTo(exactLimit); - assertThat(retained.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + assertThat(retained.key().getBytes(StandardCharsets.UTF_8)).hasSize(2048); assertThatThrownBy( () -> new SourceEvidence( SourceKind.ISSUER, exactLimit + "x", "1", "1", "stream", "0", new byte[] {1})) .isInstanceOf(IllegalArgumentException.class); + String configuredIssuer = "界".repeat(512); + SourceEvidence exactIssuer = + new SourceEvidence( + SourceKind.ISSUER, configuredIssuer, "1", "1", "stream", "0", new byte[] {1}); + assertThat(exactIssuer.scopeId()).isEqualTo(configuredIssuer); + assertThat(exactIssuer.key()).isEqualTo("ISSUER:" + configuredIssuer); UUID account = UUID.randomUUID(); SourceEvidence canonical = new SourceEvidence( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java index 9841105314..dfcf6b54d1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java @@ -23,6 +23,17 @@ class AccountIssuerAuthorityEventProducerTest { private static final String OTHER_ISSUER_ID = "https://other.example.test/issuer"; private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + @Test + void fullConfiguredMultibyteIssuerLengthIsPreservedWithoutPersistenceOrNormalization() { + Collaborators collaborators = new Collaborators(); + String exactIssuer = "界".repeat(512); + AccountIssuerAuthorityEventProducer producer = newProducer(exactIssuer, collaborators); + assertThatThrownBy(() -> producer.advance(exactIssuer + "x", UUID.randomUUID(), 1, 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact configured issuer"); + collaborators.verifyUnused(); + } + @Test void requestedIssuerMismatchIsRejectedBeforeDatabaseOrTransactionManagerInteraction() { Collaborators collaborators = new Collaborators(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java index 5076a08e1b..e47a167337 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java @@ -38,6 +38,17 @@ class AccountTenantAuthorityEventProducerTest { UUID.fromString("10000000-0000-0000-0000-000000000002"); private static final String STREAM_KEY = "account:auth-authority:v1:tenant/" + TENANT_ID; + @Test + void matchingEventDoesNotRelaxTheExistingTenantTransitionInvariant() { + TenantGenerationAuthorityEvent latest = event(TENANT_ID, UUID.randomUUID(), 4L, 5L, 7L); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 5L, 7L, STREAM_KEY, 4L, Optional.of(latest))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("uninterrupted sequence and counter progression"); + } + @Test void nilTenantAndRequestIdentitiesAreRejectedBeforePersistence() { Collaborators collaborators = new Collaborators(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java index 4e1abe5ac8..df24106f7b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -58,6 +58,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -323,7 +324,8 @@ void schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory() { workflowId, "unbound-commit", fixture.request().contentDigest())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertPublicationOwnerBindingConstraintDenial); assertThat(ownerCount(intake.canonicalTenantId(), fixture.localVersionKey())) .isEqualTo(ownerCountBefore); @@ -360,7 +362,7 @@ void canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup() { LARGE_VALUE); return null; })) - .isInstanceOf(org.jooq.exception.DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .satisfies(this::assertV24CanonicalKeyDenial); assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(retainedRowsBefore); @@ -600,7 +602,7 @@ private WorldDraftRegionCommitPlan stagingPlan( owner.canonicalTenantId(), owner.canonicalVersionId(), owner.gameDesignVersionId(), - source.tenantSlug(), + source.sourceGameTenantKey(), source.sourceGameRowId(), source.sourceGameTenantKey(), source.provenanceKind()), @@ -941,6 +943,16 @@ private void assertV24CanonicalKeyDenial(Throwable throwable) { assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); } + private void assertPublicationOwnerBindingConstraintDenial(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("ck_world_publication_attempt_owner_binding"); + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + private CaptureRequest copyRequest(CaptureRequest request, List tuples) { return new CaptureRequest( request.targetNamespace(), From a3eb1f5c9b4e55e94397d58541150701fa120a1d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:04:49 +1300 Subject: [PATCH 05/11] Store guarded World region commits with exact immutable retry proof --- .github/workflows/ci.yml | 22 + .../game-design-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 4 + .../world-runtime-and-movement.md | 4 + .../AccountJoinPostgresIntegrationTest.java | 66 +- ...horityProducerPostgresIntegrationTest.java | 20 +- ...horityProducerPostgresIntegrationTest.java | 20 +- .../impl/TenantIdentityGrpcService.java | 10 +- .../GameTenantCreationRepositoryTest.java | 73 ++ .../impl/TenantIdentityGrpcServiceTest.java | 58 +- .../WorldDraftRegionCommitEvidence.java | 51 + .../WorldDraftRegionCommitRepository.java | 235 +++++ .../tenant/WorldDraftRegionCommitService.java | 63 ++ ...29__world_guarded_region_draft_commits.sql | 392 +++++++ ...ftRegionCommitPostgresIntegrationTest.java | 983 ++++++++++++++++++ .../WorldDraftRegionCommitEvidenceTest.java | 42 + .../WorldDraftRegionCommitRepositoryTest.java | 54 + .../WorldDraftRegionCommitServiceTest.java | 86 ++ 19 files changed, 2161 insertions(+), 28 deletions(-) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 797af17588..4f290773f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2112,6 +2112,15 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Capture World guarded region commit PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-guarded-region-commit-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldDraftRegionCommitPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + - name: Verify Account authored-draft publication PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2165,6 +2174,19 @@ jobs: --strict \ --require-suite net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest \ --require-suite net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#twoRegionsAdvanceFourTuplesWithFullHistoryAndExactLostAckReplay()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#lastScopeConflictRollsBackEarlierRegionPayloadEpochsAndEntireHistory()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#disjointTupleCommitsSucceedFromTheSameRetainedBaseWithoutRebasing()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#immutableFullInputRejectsChangedBaseOtherOwnerPayloadOrderAndTuples()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#firstClaimAndExistingEpochContendersHaveOnlyOneWinner()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#concurrentExactFirstClaimReturnsOneOriginalResult()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#freezeFirstDeniesFreshStorageAndWriterFirstCompletesBeforeFreeze()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#productionGuardRejectsUnmanifestedPayloadMoveInsertDeleteEpochAndOtherFamilyWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#defaultPermissionVerifierFailsBeforeTransactionOrOwnerClaim()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#corruptCompleteResultIsRejectedOnExactReplayWithoutRewritingContent()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#staleTransactionAndWrongPayloadExecutionManifestsCannotAuthorizeRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#exactSnapshotSurvivesRollbackAndConcurrentRetryWithFullGraphReadback()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#wrongTenantVersionParentEdgeDeniesCaptureBeforeSnapshotRetention()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory()' \ diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index b92a694ac6..77631083e5 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -118,7 +118,7 @@ The request digest is `sha256:` followed by 64 lowercase hexadecimal digits over The receipt digest uses the same framing and encoding rules, with ordered preimage segments `game-design-tenant-creation-receipt/v1`, target namespace, creation-request UUID, owner-issued operation UUID, request digest, issued canonical tenant UUID, positive decimal Game Design row ID, exact source game tenant key, and `NEW_GAME_ROW`. Persisted source key and numeric row ID are private owner provenance, not selectors and not assertions about any Account key. -The candidate read-only method is `TenantIdentityService.ResolveFreshTenantCreation`. Its request carries a canonical non-nil `creation_request_id` and mandatory canonical `expected_request_digest`. The response carries exactly `schema_version=1`, `target_namespace`, `creation_request_id`, `operation_id`, `request_digest`, `canonical_tenant_id`, `source_game_row_id`, `source_game_tenant_key`, `provenance_kind=NEW_GAME_ROW`, and `evidence_digest` (the receipt digest). The receiver requires the verified mTLS peer `spiffe://firemud/ns/{target_namespace}/sa/account-service` for the same configured namespace; the bearer/JWT bypass, if needed for this method, is scoped only to this exact RPC and does not relax the peer guard or authorize another method/caller. Missing, ambiguous, changed, or digest-mismatched operation evidence fails closed using standard shared gRPC status errors; no new error enum is introduced. +The candidate read-only method is `TenantIdentityService.ResolveFreshTenantCreation`. Its request carries a canonical non-nil `creation_request_id` and mandatory canonical `expected_request_digest`; unknown protobuf fields are rejected before owner access. The response carries exactly `schema_version=1`, `target_namespace`, `creation_request_id`, `operation_id`, `request_digest`, `canonical_tenant_id`, `source_game_row_id`, `source_game_tenant_key`, `provenance_kind=NEW_GAME_ROW`, and `evidence_digest` (the receipt digest). The receiver requires the verified mTLS peer `spiffe://firemud/ns/{target_namespace}/sa/account-service` for the same configured namespace and denies an authenticated forwarded caller context; the mTLS workload identity is the sole caller identity for this read. The bearer/JWT bypass, if needed for this method, is scoped only to this exact RPC and does not relax the peer guard or authorize another method/caller. Missing, ambiguous, changed, or digest-mismatched operation evidence fails closed using standard shared gRPC status errors; no new error enum is introduced. The focused proof boundary is an owner database producer/readback test that verifies atomic row+operation commit, exact retry, changed-input/source conflict with no second row or mutation, persisted digest recomputation, immutable operation/source/receipt readback, plus RPC positive exact-Account-peer and negative wrong/missing-peer tests. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) owns exact-head execution evidence and incident history. Account must separately persist its UUID-keyed identity association before membership work, as required by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge); this owner proof creates no numeric alias. Neither unit tests nor database component execution substitutes for live workload authentication, a protected product creator, or a complete runtime admission handoff. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 724790ce40..583ad1f706 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -431,3 +431,7 @@ Entry format: - Context: two preserved #3004 helper contexts appeared running after restart and accepted continuation messages, but interrupt readback returned `pending_init` for one and `not_found` for the other. No new scoped edits or handoff supported treating either continuation as productive execution. - Outcome: Document preserved the dirty implementation, explicitly resumed the fixture context, and recorded the missing migration continuation as failed before retrying its same bounded assignment in a fresh context. No provider review was restarted; model capacity was not established as the cause. - Expected pattern: distinguish sidebar/list state and accepted dispatch from demonstrated execution. Recover only the affected bounded contexts, preserve their edits and findings, and record unavailable attempts without claiming review or validation credit. The restart-state discrepancy remains unexplained. + +- `2026-10-06`: A focused service test can build another service's dirty prerequisites + - Context: a focused Game Design tenant-readback test selected the World service's `generateJooq` through Game Design's existing test dependency while a disjoint helper was still preparing World migration V29. The selected Game Design tests did not execute because the prerequisite parser failed. + - Expected pattern: inspect cross-service test dependencies before treating a focused module command as isolated from an active helper. Serialize validation after the dependency's handoff, preserve the real prerequisite failure, and do not count unexecuted selected tests as proof. The repository's locked Gradle entrypoint does not remove task dependencies. 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 a281b4318e..cf1c6442bc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](https://github.com/benhook1013/FireMUD/actions/runs/37333148281) independently verified runner checkout and raw XML establish actual PostgreSQL execution, not local skips. All eleven Draft authorization-fence methods and the V59 retained-history/multibyte source-key case passed. Three distinct Account methods failed: issuer and tenant atomicity-denial tests inspected Spring's wrapper message rather than the correct nested PostgreSQL trigger error, and a retained-role fixture expected a second source writer to bypass the new pending-source guard. The two tenant strict-step failures are the same method, not separate defects. The correction retains the guard, proves competing-request denial and original completion, then exact historical retry after a later legitimate source advance; corrected execution remains required. Game Design and World jobs passed, but Account and aggregate readiness are not green. No producer authentication, complete source participation or activation follows from these component results. + +The corrected composed Account/Game Design/World full-check, boot-JAR, World jOOQ generation, formatting, Checkstyle, SpotBugs, coverage, links and Markdown gate passes in 1m22s (141 tasks:33 executed,108 up-to-date). Parsed unit results are Account954, Game Design517 and World265 executed cleanly; Account's unchanged unit result was reused, while Game Design and World executed in the final gate. One Game Design MinIO case and all587 PostgreSQL cases (Account381/Game Design129/World77) skip locally. Two added Game Design unit methods prove the closed fresh-creation request/caller-context guards and stored request-digest tamper denial before owner access; they do not authenticate a creator or grant first-admin authority. Flyway sanity passes for twelve sets/191 files, and230 architecture-contract tests pass. Runtime, credential and ring-mount gates remain closed. + The current authored-publication candidate connects the explicitly unwired retained `EXPLICIT_JOIN` tenant-role writer to V57 source-change ordering. V58 permits only an immutable role request linked to the exact durable `WAITING` source intent to remain pending; pending results contain no audit, member result or authorization. Once both owner outcomes permit the source change, role, membership/pair counters, authority event, audit and source completion commit in the same Account transaction. Retry reads the original source vector instead of recapturing later state, and issuance-fence invalidation participates in both the membership and independently captured Account scopes. At source `9cf395d17398fe0b7fef8fae3a9e58d59e2ed949`, raw XML from [CI37326159559](https://github.com/benhook1013/FireMUD/actions/runs/37326159559) proves all 28 strict Account PostgreSQL selections passed without skips: nine existing authorization-fence cases and nineteen retained-role/journal cases, including the four source-writer ordering/recovery and two pending-journal/migration cases. The workflow-dispatch metadata pins the source; runner checkout was not independently verified. The actor UUID is still a row selector, not authenticated caller proof, and creator bootstrap, hosted-terms sources and authenticated owner-result producers remain open. The next candidate extends that ordering to the existing unwired issuer and tenant authority-event producers. V59 journals each exact `(source kind, scope, request UUID)` with one independently allocated source-change UUID, original request bytes and independently captured counters, checkpoint and event. An unresolved attempt commits only `WAITING` intent; actual source counters, outbox event, exact readback and both source-journal completions share the eventual Account transaction. A distinct overlapping pending source claim is denied before storing a competing stale capture, while exact retries and disjoint sources remain supported. V59 widens the exact source participation key without truncation or aliases and preserves V58 source/event history without backfill. Thirteen new producer and two shared-fence PostgreSQL cases are defined and required by CI; their execution remains unproved locally without Docker. This does not authenticate a caller, implement every Account-wide or hosted-terms source writer, enable an RPC, or complete the authoring fence. 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 63e5a8470a..e527819fe8 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The guarded REGION storage candidate adds V29 and an explicitly unwired owner-local service over the existing World tables. The complete immutable Draft input and source-qualified V27 association bind the transaction; it derives and compares both REGION aggregate and REGION_SUBTREE epochs, writes all selected existing region rows, advances their epochs and retains the full six-family graph and exact result together. A single-use transaction-specific OLD/NEW execution manifest narrows the V24 write denial only for those exact transitions; ordinary legacy writes remain denied. Durable replay verifies the complete retained result, and a late conflict must roll back content, epochs and history together. The default permission verifier denies before opening a transaction, and successful synthetic component storage reports only `STORED_PERMISSION_UNVERIFIED`, never authenticated `APPLIED`. The twelve new PostgreSQL definitions include races, rollback, changed-input and corrupt-result denial, freeze ordering, invalid-manifest denial and retained V28-to-V29 migration; all compile but skip locally without Docker, so their execution remains open. The corrected three-service full-check/JAR/schema/docs gate passes in 1m22s with World265 clean unit results; these remain component checks, not runtime activation. + +At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](https://github.com/benhook1013/FireMUD/actions/runs/37333148281) World Build and Test succeeded. Independently parsed raw XML proves all eight authored-graph and eight publication-fence cases executed with zero skips, failures or errors, including the six corrected graph fixtures. Runner checkout logs independently identify that exact source. Game Design's coordination and selection cases also passed, but Account failed three distinct assertions/fixture expectations; aggregate green is not claimed. This execution predates V29 guarded REGION storage and establishes neither its database proof nor authenticated commit authority, synchronized normal reads, released topology or the canonical Game Session instance-to-World run lifecycle handoff. + The current publication candidate reuses one six-family database graph reader for both FROZEN capture and explicitly unwired OPEN region staging. OPEN staging resolves committed intake and V27 private keys under the existing owner lock, checks the enclosing commit's exact Game Design source provenance, and returns immutable unverified content without applying it or advancing synchronized visibility. At source `9cf395d17398fe0b7fef8fae3a9e58d59e2ed949`, raw XML from [CI37326159559](https://github.com/benhook1013/FireMUD/actions/runs/37326159559) records all eight publication-fence PostgreSQL cases passing and all eight graph cases executing: two passed and six failed, with no skips. Four staging fixtures supplied a blank Game Design tenant key; two schema-denial assertions expected jOOQ exceptions instead of Spring's translated `DataIntegrityViolationException`. The fixtures now use the exact retained intake source key and check the actual translated exception plus SQLSTATE `23514` and the applicable owner constraint, preserving no-mutation assertions. Workflow-dispatch metadata pins the source; runner checkout was not independently verified. Corrected execution remains open; staged representation and freeze storage still do not prove an authenticated owner apply, synchronized normal reads, release eligibility, fresh canonical content production or runtime topology materialization. The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 241d348f8d..bde2710b4b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -2191,17 +2191,24 @@ void tenantRolePendingRetryRejectsChangedIdentityAndNeverRecapturesLaterSource() } syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.COMMITTED); - // A separately identified source writer wins the same original version after settlement. - assertThat( - tenantRoleMutationService - .mutate(roleRequest(fixture, Action.GRANT_DESIGNER, 2L)) - .status()) - .isEqualTo("COMMITTED"); - Map afterWinner = membershipAuthorityReadEvidenceSnapshot(fixture.target()); - assertThatThrownBy(() -> restartedRoleMutation(request)) - .isInstanceOf(AccountTenantRoleOperationRepository.OperationConflictException.class) - .hasMessageContaining("membership version is stale"); - assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(afterWinner); + // A distinct source writer cannot capture the same source while the original intent waits. + Request competing = roleRequest(fixture, Action.GRANT_DESIGNER, 2L); + Map beforeCompeting = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditsBeforeCompeting = countAuditOutboxRows(fixture.admin()); + assertThatThrownBy(() -> tenantRoleMutationService.mutate(competing)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Another authority source change is already pending"); + assertTenantRoleOperationAbsent(competing.requestId()); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())) + .isEqualTo(beforeCompeting); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditsBeforeCompeting); + assertPendingRoleIntent( + new TransactionTemplate(transactionManager) + .execute( + status -> + tenantRoleOperationRepository + .findForUpdate(request.requestId()) + .orElseThrow())); assertThat(originalRoleSourceChange(request).canonicalBytes()) .containsExactly(original.canonicalBytes()); assertThat( @@ -2212,6 +2219,43 @@ void tenantRolePendingRetryRejectsChangedIdentityAndNeverRecapturesLaterSource() .readSourceChange(original) .status())) .isEqualTo("WAITING"); + + OperationEvidence committed = restartedRoleMutation(request); + assertThat(committed.pending()).isFalse(); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertCurrentRoleMutationState( + fixture.target(), 3L, 1L, 2L, 1L, List.of("designer", "player"), false); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + new DraftAuthorizationFenceRepository(dsl) + .readSourceChange(original) + .status())) + .isEqualTo("SOURCE_COMMITTED"); + + // A later distinct role operation uses the newly committed source version. + Request later = roleRequest(fixture, Action.REVOKE_DESIGNER, 3L); + OperationEvidence laterCommitted = tenantRoleMutationService.mutate(later); + assertThat(laterCommitted.status()).isEqualTo("COMMITTED"); + assertCurrentRoleMutationState(fixture.target(), 4L, 2L, 3L, 2L, List.of("player"), true); + Map afterLaterCommit = + membershipAuthorityReadEvidenceSnapshot(fixture.target()); + assertExactTenantRoleOperation(committed, restartedRoleMutation(request)); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())) + .isEqualTo(afterLaterCommit); + assertThat(originalRoleSourceChange(request).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + new DraftAuthorizationFenceRepository(dsl) + .readSourceChange(original) + .status())) + .isEqualTo("SOURCE_COMMITTED"); } private Request roleRequest(TenantRoleFixture fixture, Action action, long targetVersion) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index aa93caf953..3bec1913f9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -42,6 +42,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -166,8 +167,14 @@ void issuerRevocationWaitsForBothExactAbortsAndPendingRequestAndCaptureAreImmuta fences.markSourceCommitted(original); return null; })) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining("must commit atomically"); + .satisfies( + failure -> { + PSQLException postgresFailure = rootPostgresCause(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat((Throwable) postgresFailure) + .hasMessageContaining( + "Issuer/tenant journal and V57 source transition must commit atomically"); + }); assertThat(fixture.producer().advance(ISSUER_ID, request, 1, 1).issuerAuthGeneration()) .isEqualTo("2"); assertThatThrownBy( @@ -1262,6 +1269,15 @@ private void await(CountDownLatch latch) { } } + private static PSQLException rootPostgresCause(Throwable failure) { + Throwable cause = failure; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + return (PSQLException) cause; + } + private T transaction(TransactionTemplate transaction, Supplier operation) { return transaction.execute(status -> operation.get()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java index 3ddbf75fb4..30a9745d74 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java @@ -46,6 +46,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -168,8 +169,14 @@ void tenantRevocationWaitsForExactAbortsAndKeepsOriginalPendingRequestAndCapture fences.markSourceCommitted(original); return null; })) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining("must commit atomically"); + .satisfies( + failure -> { + PSQLException postgresFailure = rootPostgresCause(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat((Throwable) postgresFailure) + .hasMessageContaining( + "Issuer/tenant journal and V57 source transition must commit atomically"); + }); fixture.producer().advance(TENANT_ID, request, 1, 1); assertThatThrownBy( () -> @@ -1280,6 +1287,15 @@ private void await(CountDownLatch latch) { } } + private static PSQLException rootPostgresCause(Throwable failure) { + Throwable cause = failure; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + return (PSQLException) cause; + } + private T transaction(TransactionTemplate transaction, Supplier operation) { return transaction.execute(status -> operation.get()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 46a0692108..2c0cfa4837 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -7,6 +7,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -205,19 +206,20 @@ public void resolveLegacyAccountTenantAssociation( public void resolveFreshTenantCreation( ResolveFreshTenantCreationRequest request, StreamObserver responseObserver) { - if (!isAccountPeer()) { + if (SessionContext.hasAuthenticatedCallerContext() || !isAccountPeer()) { responseObserver.onError( Status.PERMISSION_DENIED - .withDescription("Verified Account workload identity is required") + .withDescription( + "Verified Account workload identity without caller context is required") .asRuntimeException()); return; } String expectedRequestDigest = request.getExpectedRequestDigest(); - if (!isSha256Digest(expectedRequestDigest)) { + if (!isSha256Digest(expectedRequestDigest) || !request.getUnknownFields().asMap().isEmpty()) { responseObserver.onError( Status.INVALID_ARGUMENT - .withDescription("Canonical expected request digest is required") + .withDescription("Canonical closed fresh tenant creation request is required") .asRuntimeException()); return; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java new file mode 100644 index 0000000000..95599935bc --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameTenantCreationRepositoryTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String SOURCE_KEY = "new-game-owner-key"; + private static final String NAME = "Fresh Realm"; + + @Test + void readRejectsChangedStoredRequestDigestBeforeReadingGameOwner() throws Exception { + try (var connection = + DriverManager.getConnection("jdbc:h2:mem:tenant-creation-digest;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game_tenant_creation_operations (" + + "operation_id UUID NOT NULL, schema_version INTEGER NOT NULL, " + + "target_namespace VARCHAR(63) NOT NULL, creation_request_id UUID NOT NULL, " + + "request_digest VARCHAR(71) NOT NULL, source_game_tenant_key VARCHAR(36) NOT NULL, " + + "name VARCHAR(100) NOT NULL, description VARCHAR(255), status VARCHAR(16) NOT NULL, " + + "canonical_tenant_id UUID, source_game_row_id BIGINT, " + + "provenance_kind VARCHAR(32), evidence_digest VARCHAR(71))"); + + String changedRequestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, REQUEST_ID, "different-source-key", NAME, null); + dsl.execute( + "INSERT INTO game_tenant_creation_operations (" + + "operation_id, schema_version, target_namespace, creation_request_id, " + + "request_digest, source_game_tenant_key, name, description, status, " + + "canonical_tenant_id, source_game_row_id, provenance_kind, evidence_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, NULL, 'COMPLETED', ?, 91, 'NEW_GAME_ROW', ?)", + OPERATION_ID, + NAMESPACE, + REQUEST_ID, + changedRequestDigest, + SOURCE_KEY, + NAME, + TENANT_ID, + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + REQUEST_ID, + OPERATION_ID, + changedRequestDigest, + TENANT_ID, + 91L, + SOURCE_KEY, + "NEW_GAME_ROW")); + + GameRepository gameRepository = mock(GameRepository.class); + GameTenantCreationRepository repository = + new GameTenantCreationRepository(dsl, gameRepository); + + assertThatThrownBy(() -> repository.read(REQUEST_ID, NAMESPACE)) + .isInstanceOf(GameTenantCreationRepository.InvalidCreationEvidenceException.class) + .hasMessageContaining("request digest does not match"); + verifyNoInteractions(gameRepository); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index ae3d687b19..e898e86792 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -17,9 +17,12 @@ import io.grpc.stub.StreamObserver; import java.sql.SQLException; import java.util.Base64; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -443,6 +446,32 @@ void freshCreationReadRejectsEmptyAlternateAndNilIdsOrDigestsBeforeOwnerRead() { verifyNoInteractions(creationRepository); } + @Test + void freshCreationReadRejectsUnknownFieldsAndAuthenticatedCallerContextBeforeOwnerRead() { + ResolveFreshTenantCreationRequest request = + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(FRESH_CREATION_REQUEST_ID.toString()) + .setExpectedRequestDigest(FRESH_REQUEST_DIGEST) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + + FreshCreationObserver unknownFields = freshCreationCall(request, ACCOUNT_PEER, false); + FreshCreationObserver authenticatedContext = + freshCreationCall( + request.toBuilder().setUnknownFields(UnknownFieldSet.getDefaultInstance()).build(), + ACCOUNT_PEER, + true); + + assertEquals(Status.Code.INVALID_ARGUMENT, freshCreationStatus(unknownFields)); + assertEquals(Status.Code.PERMISSION_DENIED, freshCreationStatus(authenticatedContext)); + assertNull(unknownFields.value); + assertNull(authenticatedContext.value); + verifyNoInteractions(creationRepository); + } + @Test void freshCreationReadReturnsNotFoundOnlyForExactAbsentRequest() { UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -834,6 +863,17 @@ private AssociationObserver associationCall(long accountTenantId, String peerUri private FreshCreationObserver freshCreationCall( String creationRequestId, String expectedRequestDigest, String peerUri) { + return freshCreationCall( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(creationRequestId) + .setExpectedRequestDigest(expectedRequestDigest) + .build(), + peerUri, + false); + } + + private FreshCreationObserver freshCreationCall( + ResolveFreshTenantCreationRequest request, String peerUri, boolean authenticatedContext) { FreshCreationObserver observer = new FreshCreationObserver(); Context context = Context.current(); if (peerUri != null) { @@ -841,14 +881,16 @@ private FreshCreationObserver freshCreationCall( context.withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); } - context.run( - () -> - service.resolveFreshTenantCreation( - ResolveFreshTenantCreationRequest.newBuilder() - .setCreationRequestId(creationRequestId) - .setExpectedRequestDigest(expectedRequestDigest) - .build(), - observer)); + if (authenticatedContext) { + SessionContext.setContext(FRESH_CANONICAL_TENANT_ID.toString(), List.of(), Map.of()); + } + try { + context.run(() -> service.resolveFreshTenantCreation(request, observer)); + } finally { + if (authenticatedContext) { + SessionContext.clear(); + } + } return observer; } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java new file mode 100644 index 0000000000..379b204648 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Immutable component storage evidence; never Account permission, APPLIED, or fence release proof. + */ +public final class WorldDraftRegionCommitEvidence { + public static final String STATUS = "STORED_PERMISSION_UNVERIFIED"; + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] graphBytes; + private final byte[] resultBytes; + + WorldDraftRegionCommitEvidence( + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] graphBytes, + byte[] resultBytes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + if (graphBytes.length == 0 || resultBytes.length == 0) { + throw new IllegalArgumentException("Complete graph and storage result bytes are required"); + } + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java new file mode 100644 index 0000000000..6d6b471555 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete region storage over existing owner tables. Immutable graphs are historical evidence, + * never another mutable graph or a publication checkpoint. This component has no runtime bean. + */ +public class WorldDraftRegionCommitRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final WorldAuthoredGraphReader reader; + private final WorldDraftRegionGraphStager stager; + private final ObjectMapper mapper; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this unwired component has no finalizer.") + public WorldDraftRegionCommitRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + reader = new WorldAuthoredGraphReader(dsl); + stager = new WorldDraftRegionGraphStager(); + } + + WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + requireTransaction(); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + WorldDraftRegionCommitEvidence replay = find(plan, ownerJson); + if (replay != null) { + return replay; + } + OpenOwner owner = fence.lockOpenAndResolve(plan.ownerBinding()); + requireSource(plan, owner); + // First claims and all same-Version writers/freeze share the V25 row. A contender may have + // completed while this transaction waited, so retry lookup must follow lock acquisition too. + replay = find(plan, ownerJson); + if (replay != null) { + return replay; + } + WorldAuthoredGraph before = + reader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()); + WorldAuthoredGraph staged = stager.stage(plan, before).graph(); + List> changes = changes(plan, staged); + dsl.resultQuery( + "SELECT world_store_guarded_region_rows(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + mapper.writeValueAsString(changes)) + .fetch(); + byte[] graphBytes = + reader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()).encode(mapper); + if (!Arrays.equals(staged.encode(mapper), graphBytes)) { + throw new ConflictException("Stored World graph differs from the complete staged operation"); + } + byte[] resultBytes = encodeResult(plan, graphBytes); + dsl.execute( + "INSERT INTO world_region_draft_commit (target_namespace, canonical_tenant_id, canonical_version_id, " + + "request_id, commit_id, version_identity_operation_id, local_tenant_key, local_version_key, " + + "owner_binding_json, binding_json, binding_digest, graph_bytes, graph_sha256, result_bytes, storage_status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + plan.ownerBinding().targetNamespace(), + plan.binding().target().canonicalTenantId(), + plan.binding().target().canonicalVersionId(), + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + owner.localTenantKey(), + owner.localVersionKey(), + ownerJson, + plan.binding().canonicalJson(), + plan.binding().digest(), + graphBytes, + sha256(graphBytes), + resultBytes, + WorldDraftRegionCommitEvidence.STATUS); + return new WorldDraftRegionCommitEvidence( + plan.binding(), plan.ownerBinding(), graphBytes, resultBytes); + } + + private byte[] encodeResult(WorldDraftRegionCommitPlan plan, byte[] graphBytes) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldDraftRegionCommitEvidence.STATUS); + result.put("requestId", plan.binding().requestId().toString()); + result.put("commitId", plan.binding().commitId().toString()); + result.put("bindingDigest", plan.binding().digest()); + result.put("ownerBinding", plan.ownerBinding()); + result.put("graphSha256", sha256(graphBytes)); + result.put( + "affectedEpochsAfter", + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", unit.aggregateType()); + after.put("aggregateId", unit.aggregateId()); + after.put("scopeType", unit.scopeType()); + after.put("scopeId", unit.scopeId()); + after.put("epoch", Long.toString(Long.parseLong(unit.expectedEpoch()) + 1)); + return after; + }) + .toList()); + return mapper.writeValueAsBytes(result); + } + + private WorldDraftRegionCommitEvidence find(WorldDraftRegionCommitPlan plan, String ownerJson) { + // Request and commit identities cannot be silently reused under a different canonical target. + List rows = + dsl.resultQuery( + "SELECT c.*, v.local_tenant_key AS identity_tenant_key FROM world_region_draft_commit c " + + "JOIN world_authored_version_identity v ON v.operation_id = c.version_identity_operation_id " + + "WHERE c.request_id = ? OR c.commit_id = ?", + plan.binding().requestId(), + plan.binding().commitId()) + .fetch(); + if (rows.isEmpty()) { + return null; + } + if (rows.size() != 1) { + throw new ConflictException("World complete request and commit select conflicting history"); + } + Record row = rows.get(0); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + if (!binding.equals(plan.binding()) + || !ownerJson.equals(row.get("owner_binding_json", String.class))) { + throw new ConflictException( + "World complete request or commit was reused with changed full input or source"); + } + if (!Objects.equals( + row.get("target_namespace", String.class), plan.ownerBinding().targetNamespace()) + || !Objects.equals( + row.get("canonical_tenant_id", java.util.UUID.class), + binding.target().canonicalTenantId()) + || !Objects.equals( + row.get("canonical_version_id", java.util.UUID.class), + binding.target().canonicalVersionId()) + || !Objects.equals(row.get("request_id", java.util.UUID.class), binding.requestId()) + || !Objects.equals(row.get("commit_id", java.util.UUID.class), binding.commitId()) + || !Objects.equals( + row.get("version_identity_operation_id", java.util.UUID.class), + plan.ownerBinding().versionIdentityOperationId()) + || !Objects.equals( + row.get("local_tenant_key", Long.class), row.get("identity_tenant_key", Long.class))) { + throw new ConflictException( + "World complete immutable storage history has inconsistent identity provenance"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + if (!sha256(graph).equals(row.get("graph_sha256", String.class)) + || !WorldDraftRegionCommitEvidence.STATUS.equals(row.get("storage_status", String.class))) { + throw new ConflictException("World complete immutable storage history is inconsistent"); + } + WorldAuthoredGraph.decode(graph, mapper); + byte[] storedResult = row.get("result_bytes", byte[].class); + if (!Arrays.equals(encodeResult(plan, graph), storedResult)) { + throw new ConflictException( + "World complete immutable result differs from its exact input, epochs or graph"); + } + return new WorldDraftRegionCommitEvidence(binding, plan.ownerBinding(), graph, storedResult); + } + + private List> changes( + WorldDraftRegionCommitPlan plan, WorldAuthoredGraph staged) { + return plan.regionRevisions().stream() + .map( + revision -> { + long id = Long.parseLong(revision.mutation().getAggregateId()); + Map region = + staged.regions().stream() + .filter(row -> Objects.equals(row.get("id"), id)) + .findFirst() + .orElseThrow(); + Map change = new LinkedHashMap<>(region); + change.put( + "expectedAggregateEpoch", + Long.toString(revision.mutation().getExpectedDraftRevisionEpoch())); + change.put( + "expectedScopeEpoch", + Long.toString(revision.mutation().getExpectedDraftScopeRevisionEpoch())); + return change; + }) + .toList(); + } + + private void requireSource(WorldDraftRegionCommitPlan plan, OpenOwner owner) { + AuthoredWorldSourceEvidence source = owner.receipt().source(); + DraftCommitBinding.TargetProof target = plan.binding().target(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new ConflictException( + "World complete commit differs from retained intake source provenance"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + java.sql.Connection.TRANSACTION_READ_COMMITTED)) { + throw new ConflictException( + "World complete storage requires writable READ COMMITTED transaction"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java new file mode 100644 index 0000000000..10444a1bea --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired complete owner-local storage component, with a fail-closed permission seam. + */ +public final class WorldDraftRegionCommitService { + /** + * Must fail unless the exact complete operation has durable Account ordering that remains held + * continuously through its terminal reconciliation. A preflight permission check is not reusable + * authorization for a later commit. No authenticated implementation is supplied in this slice; + * fixture implementations establish component storage prerequisites only. + */ + @FunctionalInterface + public interface PermissionVerifier { + void verify(WorldDraftRegionCommitPlan plan); + } + + private final WorldDraftRegionCommitRepository repository; + private final PermissionVerifier verifier; + private final TransactionTemplate transaction; + + /** Builds an unwired, denied component by default. */ + public WorldDraftRegionCommitService( + WorldDraftRegionCommitRepository repository, PlatformTransactionManager manager) { + this( + repository, + manager, + plan -> { + throw new ConflictException( + "Authenticated Account Draft commit permission is unavailable"); + }); + } + + public WorldDraftRegionCommitService( + WorldDraftRegionCommitRepository repository, + PlatformTransactionManager manager, + PermissionVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** Verifies before opening the dedicated transaction; no external call runs while it is open. */ + public WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage cannot start inside an existing transaction"); + } + verifier.verify(plan); + return Objects.requireNonNull(transaction.execute(status -> repository.store(plan))); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql b/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql new file mode 100644 index 0000000000..1cfada70b8 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql @@ -0,0 +1,392 @@ +-- Complete owner-local component storage only: no Account permission or publication proof. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_region_commit_identity UNIQUE ( + operation_id, target_namespace, canonical_tenant_id, canonical_version_id, local_version_key + ); + +CREATE TABLE world_region_draft_commit ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + result_bytes BYTEA NOT NULL, + storage_status VARCHAR(32) NOT NULL, + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_region_commit_identity FOREIGN KEY ( + version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ), + CONSTRAINT ck_world_region_commit_evidence CHECK ( + binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 AND octet_length(result_bytes) > 0 + AND storage_status = 'STORED_PERMISSION_UNVERIFIED' + AND local_tenant_key > 0 AND local_version_key > 0 + ) +); + +-- The function below creates and consumes these exact row transitions within its execution. +-- No manifest survives the function, and ordinary application code never inserts one. +CREATE TABLE world_region_draft_execution_manifest ( + transaction_id BIGINT NOT NULL, + operation_id UUID NOT NULL, + table_name VARCHAR(50) NOT NULL, + row_id BIGINT NOT NULL, + row_operation TEXT NOT NULL, + version_identity_operation_id UUID NOT NULL REFERENCES world_authored_version_identity(operation_id), + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding JSONB NOT NULL, + complete_binding JSONB NOT NULL, + expected_old JSONB, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, operation_id, table_name, row_id), + CHECK (table_name IN ('region', 'world_design_aggregate_epoch', 'world_design_scope_epoch')), + CHECK (row_operation IN ('INSERT', 'UPDATE')), + CHECK ((row_operation = 'INSERT' AND expected_old IS NULL AND table_name <> 'region') + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL)) +); + +-- [jooq ignore start] +REVOKE ALL ON world_region_draft_execution_manifest FROM PUBLIC; + +CREATE TRIGGER trg_world_region_commit_immutable + BEFORE UPDATE OR DELETE ON world_region_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_region_commit_no_truncate + BEFORE TRUNCATE ON world_region_draft_commit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_consume_region_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation NOT IN ('INSERT', 'UPDATE') OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_region_draft_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_design_publication_fence_owner o + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table AND m.row_operation = actual_operation + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NOT DISTINCT FROM actual_old + AND m.expected_new = actual_new + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.local_version_key = (actual_new->>'version_id')::BIGINT + AND v.operation_id = m.version_identity_operation_id + AND v.local_tenant_key = m.local_tenant_key + AND v.local_version_key = m.local_version_key + AND v.operation_id::TEXT = m.owner_binding->>'versionIdentityOperationId' + AND v.target_namespace = m.owner_binding->>'targetNamespace' + AND v.canonical_tenant_id::TEXT = m.owner_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.owner_binding->>'canonicalVersionId' + AND v.intake_operation_id::TEXT = m.owner_binding->>'intakeOperationId' + AND v.intake_request_id::TEXT = m.owner_binding->>'intakeRequestId' + AND v.intake_request_digest = m.owner_binding->>'intakeRequestDigest' + AND v.source_operation_id::TEXT = m.owner_binding->>'sourceOperationId' + AND v.source_evidence_digest = m.owner_binding->>'sourceEvidenceDigest' + AND v.intake_receipt_digest = m.owner_binding->>'intakeReceiptDigest' + AND v.game_design_version_id = (m.owner_binding->>'gameDesignVersionId')::BIGINT + AND v.canonical_tenant_id::TEXT = m.complete_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.complete_binding->>'canonicalVersionId' + AND m.operation_id::TEXT = m.complete_binding->>'commitId' + AND o.target_namespace = v.target_namespace + AND o.canonical_tenant_id = v.canonical_tenant_id + AND o.local_tenant_key = v.local_tenant_key AND o.version_id = v.local_version_key + AND o.owner_freeze_phase = 'OPEN' AND o.current_publication_fence IS NULL + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_region_execution_manifest(TEXT, TEXT, JSONB, JSONB) FROM PUBLIC; + +-- Retain the V24 deny boundary everywhere except an exact, single-use transition created by +-- the dedicated function. Moving a row out of a canonical tenant still enters this branch. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest(TG_TABLE_NAME, TG_OP, old_row, new_row) + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +-- p_changes is the trusted component's typed, independently scope-validated complete World +-- subset. It grants no permission. Its tuples are rechecked against the retained full binding. +-- Neither a tenant allowlist nor a session flag can enable a guarded row write. +CREATE FUNCTION world_store_guarded_region_rows(p_owner JSONB, p_binding JSONB, p_changes JSONB) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + old_region "${serviceSchema}".region%ROWTYPE; + new_region "${serviceSchema}".region%ROWTYPE; + old_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + new_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + old_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + new_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + change JSONB; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_aggregate BIGINT; + expected_scope BIGINT; + aggregate_exists BOOLEAN; + scope_exists BOOLEAN; + affected INTEGER; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR jsonb_typeof(p_changes) <> 'array' OR jsonb_array_length(p_changes) = 0 + THEN + RAISE EXCEPTION 'Complete World region storage requires writable READ COMMITTED input' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World region storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(DISTINCT value->>'id') FROM jsonb_array_elements(p_changes)) + <> jsonb_array_length(p_changes) THEN + RAISE EXCEPTION 'World complete region storage has duplicate region targets' + USING ERRCODE = '23514'; + END IF; + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'AGGREGATE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedAggregateEpoch'), + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'REGION_SUBTREE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedScopeEpoch')); + END LOOP; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType'), '[]'::JSONB) + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType') + INTO expected_units FROM jsonb_array_elements(expected_units); + IF supplied_units IS DISTINCT FROM expected_units THEN + RAISE EXCEPTION 'World complete storage requires every exact REGION and REGION_SUBTREE tuple' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_changes) + WHERE (value->>'expectedAggregateEpoch')::BIGINT < 0 + OR (value->>'expectedAggregateEpoch')::BIGINT = 9223372036854775807 + OR (value->>'expectedScopeEpoch')::BIGINT < 0 + OR (value->>'expectedScopeEpoch')::BIGINT = 9223372036854775807) THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_aggregate := (change->>'expectedAggregateEpoch')::BIGINT; + expected_scope := (change->>'expectedScopeEpoch')::BIGINT; + IF expected_aggregate < 0 OR expected_aggregate = 9223372036854775807 + OR expected_scope < 0 OR expected_scope = 9223372036854775807 THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT old_region FROM "${serviceSchema}".region + WHERE id = (change->>'id')::BIGINT AND tenant_id = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + new_region := old_region; + new_region.name := change->>'name'; + new_region.shard_id := (change->>'shardId')::INTEGER; + new_region.weather := change->>'weather'; + new_region.generation_seed := (change->>'generationSeed')::BIGINT; + new_region.generator_type := change->>'generatorType'; + new_region.generator_params := change->>'generatorParams'; + new_region.spacing_multiplier := (change->>'spacingMultiplier')::DOUBLE PRECISION; + IF new_region.name IS NULL OR btrim(new_region.name) = '' OR new_region.shard_id < 0 + OR new_region.spacing_multiplier <= 0 + OR new_region.spacing_multiplier IN ('NaN'::DOUBLE PRECISION, 'Infinity'::DOUBLE PRECISION) THEN + RAISE EXCEPTION 'World region payload is invalid' USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'region', old_region.id, 'UPDATE', + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, to_jsonb(old_region), to_jsonb(new_region)); + UPDATE "${serviceSchema}".region SET name = new_region.name, shard_id = new_region.shard_id, + weather = new_region.weather, generation_seed = new_region.generation_seed, + generator_type = new_region.generator_type, generator_params = new_region.generator_params, + spacing_multiplier = new_region.spacing_multiplier + WHERE id = old_region.id AND to_jsonb(region) = to_jsonb(old_region); + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'World region changed during complete storage' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_aggregate FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND aggregate_type = 'REGION' AND aggregate_id = old_region.id FOR UPDATE; + aggregate_exists := FOUND; + IF (aggregate_exists AND old_aggregate.draft_revision_epoch <> expected_aggregate) + OR (NOT aggregate_exists AND expected_aggregate <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate epoch' USING ERRCODE = '23514'; + END IF; + IF aggregate_exists THEN + new_aggregate := old_aggregate; + ELSE + new_aggregate.id := nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'); + new_aggregate.tenant_id := identity_row.local_tenant_key; + new_aggregate.version_id := identity_row.local_version_key; + new_aggregate.aggregate_type := 'REGION'; + new_aggregate.aggregate_id := old_region.id; + END IF; + new_aggregate.draft_revision_epoch := expected_aggregate + 1; + new_aggregate.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_aggregate_epoch', new_aggregate.id, + CASE WHEN aggregate_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN aggregate_exists THEN to_jsonb(old_aggregate) END, to_jsonb(new_aggregate)); + IF aggregate_exists THEN + UPDATE "${serviceSchema}".world_design_aggregate_epoch + SET draft_revision_epoch = new_aggregate.draft_revision_epoch, updated_at = new_aggregate.updated_at + WHERE id = old_aggregate.id AND draft_revision_epoch = expected_aggregate; + ELSE + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch SELECT (new_aggregate).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate CAS' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_scope FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND scope_type = 'REGION_SUBTREE' AND scope_id = old_region.id::TEXT FOR UPDATE; + scope_exists := FOUND; + IF (scope_exists AND old_scope.draft_scope_revision_epoch <> expected_scope) + OR (NOT scope_exists AND expected_scope <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE epoch' USING ERRCODE = '23514'; + END IF; + IF scope_exists THEN + new_scope := old_scope; + ELSE + new_scope.id := nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'); + new_scope.tenant_id := identity_row.local_tenant_key; + new_scope.version_id := identity_row.local_version_key; + new_scope.scope_type := 'REGION_SUBTREE'; + new_scope.scope_id := old_region.id::TEXT; + END IF; + new_scope.draft_scope_revision_epoch := expected_scope + 1; + new_scope.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_scope_epoch', new_scope.id, + CASE WHEN scope_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN scope_exists THEN to_jsonb(old_scope) END, to_jsonb(new_scope)); + IF scope_exists THEN + UPDATE "${serviceSchema}".world_design_scope_epoch + SET draft_scope_revision_epoch = new_scope.draft_scope_revision_epoch, updated_at = new_scope.updated_at + WHERE id = old_scope.id AND draft_scope_revision_epoch = expected_scope; + ELSE + INSERT INTO "${serviceSchema}".world_design_scope_epoch SELECT (new_scope).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE CAS' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Complete World storage left an unconsumed execution manifest' + USING ERRCODE = '23514'; + END IF; +END; +$$; +-- Explicit internal calls only; deployment roles must deliberately grant access when an +-- authenticated producer exists. Schema owners are the trusted database administration boundary. +REVOKE ALL ON FUNCTION world_store_guarded_region_rows(JSONB, JSONB, JSONB) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..a2227098a6 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -0,0 +1,983 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Synthetic source/permission fixtures prove component storage only, never authenticated APPLIED. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftRegionCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void twoRegionsAdvanceFourTuplesWithFullHistoryAndExactLostAckReplay() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan firstPlan = plan(f, List.of(f.first(), f.second()), 0, "first"); + WorldDraftRegionCommitEvidence first = component().store(firstPlan); + assertThat(name(f.first())).isEqualTo("first-" + f.first()); + assertThat(name(f.second())).isEqualTo("first-" + f.second()); + assertEpochs(f, 1, 1); + assertThat(first.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + String graph = new String(first.graphBytes(), StandardCharsets.UTF_8); + assertThat(graph) + .contains( + "\"regions\"", + "\"zones\"", + "\"rooms\"", + "\"roomExits\"", + "\"generationRules\"", + "\"worldEntitySpawnBindings\""); + assertThat(new String(first.resultBytes(), StandardCharsets.UTF_8)) + .contains(firstPlan.binding().digest(), "\"affectedEpochsAfter\"", "\"epoch\":\"1\"") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased"); + WorldDraftRegionCommitEvidence lostAck = component().store(firstPlan); + assertThat(lostAck.graphBytes()).containsExactly(first.graphBytes()); + assertThat(lostAck.resultBytes()).containsExactly(first.resultBytes()); + component().store(plan(f, List.of(f.first(), f.second()), 1, "later")); + freeze(f); + // Historical retry precedes OPEN admission and preserves the original visibility snapshot. + WorldDraftRegionCommitEvidence historical = component().store(firstPlan); + assertThat(historical.graphBytes()).containsExactly(first.graphBytes()); + assertThat(historical.resultBytes()).containsExactly(first.resultBytes()); + assertThat(name(f.first())).startsWith("later-"); + assertEpochs(f, 2, 2); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void lastScopeConflictRollsBackEarlierRegionPayloadEpochsAndEntireHistory() { + Fixture f = fixture(); + seedScope(f, f.second(), 3); + long countBefore = count("world_region_draft_commit"); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "conflicting"); + assertThatThrownBy(() -> component().store(plan)) + .hasStackTraceContaining("DRAFT_WRITE_CONFLICT: REGION_SUBTREE"); + assertThat(name(f.first())).isEqualTo("original-first"); + assertThat(name(f.second())).isEqualTo("original-second"); + assertThat(epochCount(f, "world_design_aggregate_epoch")).isZero(); + assertThat(epochCount(f, "world_design_scope_epoch")).isEqualTo(1); + assertThat(count("world_region_draft_commit")).isEqualTo(countBefore); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void disjointTupleCommitsSucceedFromTheSameRetainedBaseWithoutRebasing() { + Fixture f = fixture(); + WorldDraftRegionCommitEvidence first = + component().store(plan(f, List.of(f.first()), 0, "first")); + WorldDraftRegionCommitEvidence second = + component().store(plan(f, List.of(f.second()), 0, "second")); + assertThat(first.binding().baseCommitId()).isEqualTo(second.binding().baseCommitId()); + assertEpochs(f, 1, 1); + assertThat(new String(first.graphBytes(), StandardCharsets.UTF_8)).contains("original-second"); + assertThat(new String(second.graphBytes(), StandardCharsets.UTF_8)) + .contains("first-", "second-"); + } + + @Test + void immutableFullInputRejectsChangedBaseOtherOwnerPayloadOrderAndTuples() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan original = plan(f, List.of(f.first(), f.second()), 0, "original"); + component().store(original); + DraftCommitBinding binding = original.binding(); + assertChanged( + original, + binding.baseCommitId() + "-changed", + binding.revisions(), + binding.affectedUnits()); + List changed = new ArrayList<>(binding.revisions()); + DraftCommitBinding.RevisionPayload other = changed.get(changed.size() - 1); + changed.set( + changed.size() - 1, + new DraftCommitBinding.RevisionPayload( + other.revisionOrder(), other.revisionId(), other.owner(), other.payload() + "changed")); + assertChanged(original, binding.baseCommitId(), changed, binding.affectedUnits()); + List reordered = + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + changed.get(1).revisionId(), + Owner.WORLD_MANAGEMENT, + binding.revisions().get(1).payload()), + new DraftCommitBinding.RevisionPayload( + "1", + changed.get(0).revisionId(), + Owner.WORLD_MANAGEMENT, + binding.revisions().get(0).payload()), + other); + assertChanged(original, binding.baseCommitId(), reordered, binding.affectedUnits()); + assertThatThrownBy( + () -> + WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.revisions(), + binding.affectedUnits().subList(1, binding.affectedUnits().size())), + original.ownerBinding())) + .isInstanceOf(IllegalArgumentException.class); + // Omitting a complete other-owner subset preserves World semantics but must conflict on replay. + assertChanged( + original, + binding.baseCommitId(), + binding.revisions().subList(0, 2), + binding.affectedUnits(Owner.WORLD_MANAGEMENT)); + assertEpochs(f, 1, 1); + } + + @Test + void firstClaimAndExistingEpochContendersHaveOnlyOneWinner() throws Exception { + Fixture f = fixture(); + race(f, 0); + assertEpochs(f, 1, 1); + race(f, 1); + assertEpochs(f, 2, 2); + } + + @Test + void concurrentExactFirstClaimReturnsOneOriginalResult() throws Exception { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "same"); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + await(begin); + return component().store(plan); + }); + Future second = + executor.submit( + () -> { + await(begin); + return component().store(plan); + }); + begin.countDown(); + WorldDraftRegionCommitEvidence one = first.get(20, TimeUnit.SECONDS); + WorldDraftRegionCommitEvidence two = second.get(20, TimeUnit.SECONDS); + assertThat(two.resultBytes()).containsExactly(one.resultBytes()); + assertThat(two.graphBytes()).containsExactly(one.graphBytes()); + assertEpochs(f, 1, 1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freezeFirstDeniesFreshStorageAndWriterFirstCompletesBeforeFreeze() throws Exception { + Fixture frozen = fixture(); + freeze(frozen); + assertThatThrownBy(() -> component().store(plan(frozen, List.of(frozen.first()), 0, "denied"))) + .hasMessageContaining("not open"); + assertThat(name(frozen.first())).isEqualTo("original-first"); + Fixture writer = fixture(); + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch freezing = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + WorldDraftRegionCommitPlan writerPlan = + plan(writer, List.of(writer.first(), writer.second()), 0, "writer-first"); + WorldDraftRegionCommitRepository pausedRepository = + new WorldDraftRegionCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + WorldDraftRegionCommitEvidence evidence = super.store(plan); + locked.countDown(); + await(release); + return evidence; + } + }; + Future first = + executor.submit( + () -> + new WorldDraftRegionCommitService(pausedRepository, manager, plan -> {}) + .store(writerPlan)); + assertThat(locked.await(15, TimeUnit.SECONDS)).isTrue(); + Future freeze = + executor.submit( + () -> { + freezing.countDown(); + freeze(writer); + }); + assertThat(freezing.await(15, TimeUnit.SECONDS)).isTrue(); + assertThat(freeze.isDone()).isFalse(); + // Other connections still see the precommit complete owner graph and no result history. + assertThat(name(writer.first())).isEqualTo("original-first"); + assertThat(name(writer.second())).isEqualTo("original-second"); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_region_draft_commit WHERE request_id = ?", + writerPlan.binding().requestId()) + .fetchOne(0, Long.class)) + .isZero(); + release.countDown(); + first.get(20, TimeUnit.SECONDS); + freeze.get(20, TimeUnit.SECONDS); + assertThat(name(writer.first())).startsWith("writer-first-"); + assertThat(name(writer.second())).startsWith("writer-first-"); + assertEpochs(writer, 1, 1); + assertThatThrownBy( + () -> component().store(plan(writer, List.of(writer.first()), 0, "after-freeze"))) + .hasMessageContaining("not open"); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void productionGuardRejectsUnmanifestedPayloadMoveInsertDeleteEpochAndOtherFamilyWrites() { + Fixture f = fixture(); + component().store(plan(f, List.of(f.first()), 0, "stored")); + List denied = + List.of( + "UPDATE region SET name = 'legacy' WHERE id = " + f.first(), + "UPDATE region SET tenant_id = 123456789 WHERE id = " + f.first(), + "DELETE FROM region WHERE id = " + f.second(), + "INSERT INTO region(name,tenant_id,version_id) VALUES ('new'," + + f.intake().localTenantKey() + + "," + + f.version().localVersionKey() + + ")", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch = 99 WHERE tenant_id = " + + f.intake().localTenantKey(), + "UPDATE zone SET name = 'unmanifested' WHERE tenant_id = " + + f.intake().localTenantKey(), + "TRUNCATE world_design_scope_epoch", + "TRUNCATE world_region_draft_commit"); + for (String sql : denied) { + assertThatThrownBy(() -> ownerTransaction().execute(status -> dsl.execute(sql))) + .isInstanceOf(RuntimeException.class); + } + assertThat(name(f.first())).startsWith("stored-"); + assertThat(name(f.second())).isEqualTo("original-second"); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void defaultPermissionVerifierFailsBeforeTransactionOrOwnerClaim() { + Fixture f = fixture(); + WorldDraftRegionCommitService denied = new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> denied.store(plan(f, List.of(f.first()), 0, "denied"))) + .hasMessageContaining("permission is unavailable"); + assertThat(epochCount(f, "world_design_aggregate_epoch")).isZero(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_owner WHERE local_tenant_key = ?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void corruptCompleteResultIsRejectedOnExactReplayWithoutRewritingContent() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "retained"); + WorldDraftRegionCommitEvidence evidence = component().store(plan); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_region_draft_commit SET result_bytes = ? WHERE request_id = ?", + new byte[] {1}, + plan.binding().requestId())) + .hasStackTraceContaining("history is immutable"); + byte[] corrupt = + new String(evidence.resultBytes(), StandardCharsets.UTF_8) + .replace("\"epoch\":\"1\"", "\"epoch\":\"2\"") + .getBytes(StandardCharsets.UTF_8); + ownerTransaction() + .execute( + status -> { + // Deliberate retained-row corruption fixture only; production mutation guards stay + // intact. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + try { + dsl.execute( + "UPDATE world_region_draft_commit SET result_bytes = ? WHERE request_id = ?", + corrupt, + plan.binding().requestId()); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + return null; + }); + assertThatThrownBy(() -> component().store(plan)) + .hasMessageContaining("immutable result differs"); + assertEpochs(f, 1, 1); + assertThat(name(f.first())).startsWith("retained-"); + } + + @Test + void staleTransactionAndWrongPayloadExecutionManifestsCannotAuthorizeRows() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first()), 0, "manifest"); + ownerTransaction() + .execute( + status -> { + fence.lockOpen(f.owner()); + return null; + }); + for (boolean staleTransaction : List.of(true, false)) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + // Test-only synthetic manifests under the schema-owner administration + // role. The production + // function creates exact manifests internally; arbitrary roles receive + // no table privilege. + dsl.execute( + "INSERT INTO world_region_draft_execution_manifest " + + "SELECT txid_current() + ?, ?, 'region', r.id, 'UPDATE', ?, r.tenant_id, r.version_id, ?::jsonb, ?::jsonb, to_jsonb(r), to_jsonb(r) || '{\"name\":\"expected-only\"}'::jsonb FROM region r WHERE id = ?", + staleTransaction ? 1 : 0, + plan.binding().commitId(), + f.version().operationId(), + mapper.writeValueAsString(f.owner()), + plan.binding().canonicalJson(), + f.first()); + return dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + staleTransaction ? "expected-only" : "wrong-payload", + f.first()); + })) + .hasStackTraceContaining("no exact transaction execution manifest"); + } + assertThat(name(f.first())).isEqualTo("original-first"); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throws Exception { + Fixture f = fixture(); + WorldDraftRegionCommitEvidence prior = + component().store(plan(f, List.of(f.first(), f.second()), 0, "retained-v28")); + freeze(f); + String schema = "region_commit_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var oldConfig = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("28")); + oldConfig.load().migrate(); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(schema); + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role = 'replica'"); + Map scopes = new LinkedHashMap<>(); + scopes.put("world_authored_source_tenant_association", "local_tenant_key"); + scopes.put("world_authored_source_tenant_key_reservation", "tenant_key"); + scopes.put("world_authored_source_intake", "local_tenant_key"); + scopes.put("world_authored_version_identity", "local_tenant_key"); + scopes.put("world_design_publication_fence_attempt", "local_tenant_key"); + scopes.put("world_design_publication_fence_owner", "local_tenant_key"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch")) { + scopes.put(table, "tenant_id"); + } + try { + // Copy source-qualified synthetic retained rows into the schema while it still has V28. + for (Map.Entry scope : scopes.entrySet()) { + String override = + scope.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + retained.execute( + "INSERT INTO " + + scope.getKey() + + override + + " SELECT * FROM world_management_service." + + scope.getKey() + + " WHERE " + + scope.getValue() + + " = ?", + f.intake().localTenantKey()); + } + retained.execute( + "INSERT INTO world_authored_graph_snapshot (snapshot_id,capture_request_digest,publication_fence,target_namespace,canonical_tenant_id,canonical_version_id,version_identity_operation_id,world_slug,game_design_version_id,local_version_key,local_tenant_key,owner_binding_schema_version,intake_operation_id,intake_request_id,intake_request_digest,source_operation_id,source_evidence_digest,intake_receipt_digest,publication_request_id,request_digest,version_state_epoch,publish_workflow_id,applied_commit_id,content_digest,digest_schema_version,supplied_owned_affected_tuples_json,owner_revision_evidence_json,owner_commit_proof_status,graph_bytes,graph_sha256) " + + "SELECT ?,?,a.publication_fence,a.target_namespace,a.canonical_tenant_id,a.canonical_version_id,a.version_identity_operation_id,v.world_slug,a.game_design_version_id,a.version_id,a.local_tenant_key,a.owner_binding_schema_version,a.intake_operation_id,a.intake_request_id,a.intake_request_digest,a.source_operation_id,a.source_evidence_digest,a.intake_receipt_digest,a.publication_request_id,a.request_digest,a.version_state_epoch,a.publish_workflow_id,a.applied_commit_id,a.content_digest,a.digest_schema_version,?,?,'CAPTURED_UNVERIFIED',?,? " + + "FROM world_design_publication_fence_attempt a JOIN world_authored_version_identity v ON v.operation_id = a.version_identity_operation_id", + UUID.randomUUID(), + "a".repeat(64), + mapper.writeValueAsString(prior.binding().affectedUnits(Owner.WORLD_MANAGEMENT)), + "[\"synthetic-v28-unverified-history\"]", + prior.graphBytes(), + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(prior.graphBytes()))); + retained.execute("SET LOCAL session_replication_role = 'origin'"); + connection.commit(); + } catch (RuntimeException exception) { + connection.rollback(); + throw exception; + } + connection.setAutoCommit(true); + scopes.put("world_authored_graph_snapshot", "local_tenant_key"); + Map> before = retainedRows(retained, scopes.keySet().stream().toList()); + assertThat( + retained + .resultQuery( + "SELECT owner_commit_proof_status FROM world_authored_graph_snapshot") + .fetchOne(0, String.class)) + .isEqualTo("CAPTURED_UNVERIFIED"); + assertThat( + retained + .resultQuery( + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = 'world_region_draft_commit'", + schema) + .fetchOne(0, Long.class)) + .isZero(); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, scopes.keySet().stream().toList())).isEqualTo(before); + SingleConnectionDataSource dataSource = new SingleConnectionDataSource(connection, true); + WorldAuthoredSourceIntakeRepository retainedIntake = + new WorldAuthoredSourceIntakeRepository(retained); + WorldDesignPublicationFenceRepository retainedFence = + new WorldDesignPublicationFenceRepository(retained, retainedIntake); + WorldDraftRegionCommitService deniedFrozen = + new WorldDraftRegionCommitService( + new WorldDraftRegionCommitRepository(retained, retainedFence, mapper), + new DataSourceTransactionManager(dataSource), + plan -> {}); + assertThatThrownBy( + () -> deniedFrozen.store(plan(f, List.of(f.first()), 1, "must-remain-frozen"))) + .hasMessageContaining("not open"); + assertThat(retainedRows(retained, scopes.keySet().stream().toList())).isEqualTo(before); + assertThat( + retained + .resultQuery("SELECT COUNT(*) FROM world_region_draft_commit") + .fetchOne(0, Long.class)) + .isZero(); + } finally { + // This uniquely named schema is owned exclusively by this migration test. + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedRows(DSLContext retained, List tables) { + Map> rows = new LinkedHashMap<>(); + for (String table : tables) { + rows.put( + table, + retained + .resultQuery( + "SELECT to_jsonb(t)::TEXT FROM " + table + " t ORDER BY to_jsonb(t)::TEXT") + .fetch(0, String.class)); + } + return rows; + } + + private void race(Fixture f, long epoch) throws Exception { + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + WorldDraftRegionCommitPlan one = plan(f, List.of(f.first(), f.second()), epoch, "one"); + WorldDraftRegionCommitPlan two = plan(f, List.of(f.first(), f.second()), epoch, "two"); + Future first = executor.submit(() -> contend(one, begin)); + Future second = executor.submit(() -> contend(two, begin)); + begin.countDown(); + assertThat(List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + private boolean contend(WorldDraftRegionCommitPlan plan, CountDownLatch begin) { + await(begin); + try { + component().store(plan); + return true; + } catch (RuntimeException exception) { + assertThat(exception).hasStackTraceContaining("DRAFT_WRITE_CONFLICT"); + return false; + } + } + + private void assertChanged( + WorldDraftRegionCommitPlan original, + String base, + List revisions, + List units) { + DraftCommitBinding prior = original.binding(); + WorldDraftRegionCommitPlan changed = + WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create( + prior.target(), prior.requestId(), prior.commitId(), base, revisions, units), + original.ownerBinding()); + assertThatThrownBy(() -> component().store(changed)).hasMessageContaining("changed full input"); + } + + private WorldDraftRegionCommitPlan plan(Fixture f, List regions, long epoch, String name) { + UUID request = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + for (long region : regions) { + UUID revision = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(commit.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(Long.toString(region)) + .setExpectedDraftRevisionEpoch(epoch) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(region)) + .setExpectedDraftScopeRevisionEpoch(epoch) + .setRegion( + RegionDesignMutation.newBuilder() + .setName(name + "-" + region) + .setShardId(7) + .setWeather("rain") + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}") + .setSpacingMultiplier(2.0)) + .build(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision, + Owner.WORLD_MANAGEMENT, + json(mutation))); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "AGGREGATE", + Long.toString(region), + Long.toString(epoch))); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "REGION_SUBTREE", + Long.toString(region), + Long.toString(epoch))); + } + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque other owner payload")); + units.add(new AffectedUnit(Owner.ENTITY_MANAGEMENT, "ITEM", "17", "AGGREGATE", "17", "4")); + AuthoredWorldSourceEvidence source = f.intake().source(); + DraftCommitBinding.TargetProof target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create(target, request, commit, "retained-base", revisions, units), + f.owner()); + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + // Only this setup disables V24. The tested writer always runs with production + // guards restored. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + long first; + long second; + try { + first = + insertId( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('original-first',?,?) RETURNING id", + intake.localTenantKey(), + version.localVersionKey()); + second = + insertId( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('original-second',?,?) RETURNING id", + intake.localTenantKey(), + version.localVersionKey()); + long zone = + insertId( + "INSERT INTO zone(region_id,name,tenant_id,version_id) VALUES (?,'zone',?,?) RETURNING id", + first, + intake.localTenantKey(), + version.localVersionKey()); + long room = + insertId( + "INSERT INTO room(zone_id,name,tenant_id,version_id) VALUES (?,'room',?,?) RETURNING id", + zone, + intake.localTenantKey(), + version.localVersionKey()); + dsl.execute( + "INSERT INTO room_exit(tenant_id,version_id,from_room_id,to_room_id,direction,cost) VALUES (?,?,?,?,'NORTH',1)", + intake.localTenantKey(), + version.localVersionKey(), + room, + room); + dsl.execute( + "INSERT INTO generation_rule(tenant_id,version_id,name,scope_type,scope_id,value) VALUES (?,?,'rule','REGION_SUBTREE',?,'seeded')", + intake.localTenantKey(), + version.localVersionKey(), + Long.toString(first)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding(tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds) VALUES (?,?,?,'NPC',1,1,0)", + intake.localTenantKey(), + version.localVersionKey(), + room); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + assertOrigin(); + return new Fixture(intake, version, owner, first, second); + })); + } + + private void seedScope(Fixture f, long region, long epoch) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + try { + dsl.execute( + "INSERT INTO world_design_scope_epoch(tenant_id,version_id,scope_type,scope_id,draft_scope_revision_epoch) VALUES (?,?,'REGION_SUBTREE',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + Long.toString(region), + epoch); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + return null; + }); + } + + private void freeze(Fixture f) { + OwnerBinding o = f.owner(); + String request = "freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "synthetic-unverified-checkpoint", "b".repeat(64), 2))); + } + + private WorldDraftRegionCommitService component() { + return new WorldDraftRegionCommitService( + repository(), + manager, + plan -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic prerequisite only. No authenticated permission, APPLIED, or release evidence. + }); + } + + private WorldDraftRegionCommitRepository repository() { + return new WorldDraftRegionCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private String name(long region) { + return dsl.resultQuery("SELECT name FROM region WHERE id = ?", region) + .fetchOne(0, String.class); + } + + private long insertId(String sql, Object... values) { + return Objects.requireNonNull(dsl.resultQuery(sql, values).fetchOne(0, Long.class)); + } + + private long count(String table) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class)); + } + + private long epochCount(Fixture f, String table) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ? AND version_id = ?", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class)); + } + + private void assertEpochs(Fixture f, long aggregate, long scope) { + assertThat( + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch WHERE tenant_id = ? AND version_id = ? ORDER BY aggregate_id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetch(0, Long.class)) + .containsExactly(aggregate, aggregate); + assertThat( + dsl.resultQuery( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch WHERE tenant_id = ? AND version_id = ? ORDER BY scope_id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetch(0, Long.class)) + .containsExactly(scope, scope); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Storage barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner, + long first, + long second) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java new file mode 100644 index 0000000000..03ee2b01db --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionCommitEvidenceTest { + @Test + void graphAndResultBytesAreDefensiveAndRemainExplicitlyUnverifiedPermission() { + byte[] graph = {1, 2}; + byte[] result = {3, 4}; + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + WorldDraftRegionCommitEvidence evidence = + new WorldDraftRegionCommitEvidence(binding, owner, graph, result); + graph[0] = 9; + result[0] = 9; + evidence.graphBytes()[0] = 8; + evidence.resultBytes()[0] = 8; + assertThat(evidence.graphBytes()).containsExactly((byte) 1, (byte) 2); + assertThat(evidence.resultBytes()).containsExactly((byte) 3, (byte) 4); + assertThat(evidence.binding()).isSameAs(binding); + assertThat(evidence.ownerBinding()).isSameAs(owner); + assertThat(evidence.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + } + + @Test + void incompleteEvidenceCannotBeReturnedAsSuccessfulComponentStorage() { + assertThatThrownBy( + () -> + new WorldDraftRegionCommitEvidence( + mock(DraftCommitBinding.class), + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), + new byte[0], + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java new file mode 100644 index 0000000000..91c2f15949 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.sql.Connection; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldDraftRegionCommitRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final WorldDraftRegionCommitRepository repository = + new WorldDraftRegionCommitRepository(dsl, fence, new ObjectMapper()); + private final WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentTransactionCannotResolveOrTouchHistory() { + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void readOnlyTransactionCannotResolveOrTouchHistory() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void repeatableReadCannotUseReadCommittedReplayAndOwnerLockOrdering() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java new file mode 100644 index 0000000000..755eb72fd6 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDraftRegionCommitServiceTest { + private final WorldDraftRegionCommitRepository repository = + mock(WorldDraftRegionCommitRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldDraftRegionCommitService.PermissionVerifier verifier = + mock(WorldDraftRegionCommitService.PermissionVerifier.class); + private final WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultDenialCannotStartTransactionOrAccessOwnerStorage() { + WorldDraftRegionCommitService service = new WorldDraftRegionCommitService(repository, manager); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("permission is unavailable"); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsCallerTransactionBeforeVerifierCouldMakeAnExternalCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("existing transaction"); + verifyNoInteractions(verifier, repository, manager); + } + + @Test + void syntheticVerifierPrecedesDedicatedWritableReadCommittedTransactionAndCommit() { + // This sequencing fixture is not authenticated Account ordering or fence release proof. + TransactionStatus status = mock(TransactionStatus.class); + WorldDraftRegionCommitEvidence evidence = mock(WorldDraftRegionCommitEvidence.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenReturn(evidence); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThat(service.store(plan)).isSameAs(evidence); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + InOrder order = inOrder(verifier, manager, repository); + order.verify(verifier).verify(plan); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).store(plan); + order.verify(manager).commit(status); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void localFailureRollsBackWithoutReturningStorageEvidence() { + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenThrow(new IllegalStateException("late tuple conflict")); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessage("late tuple conflict"); + InOrder order = inOrder(manager, repository); + order.verify(manager).getTransaction(any()); + order.verify(repository).store(plan); + order.verify(manager).rollback(status); + } +} From af8342453753db41271518db583e97fc0e1c2351 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:27:22 +1300 Subject: [PATCH 06/11] Converge concurrent Draft claims and preserve retained World upgrade proof --- .github/workflows/ci.yml | 2 + ...ame-authoring-publishing-and-activation.md | 2 + .../world-runtime-and-movement.md | 2 + .../DraftCommitCoordinatorRepository.java | 68 +++------ ...tCoordinatorRepositoryIntegrationTest.java | 140 ++++++++++++++++++ ...ftRegionCommitPostgresIntegrationTest.java | 26 +++- 6 files changed, 193 insertions(+), 47 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f290773f5..7eae02480a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2150,6 +2150,8 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#exactClaimReplayRetainsFullBindingAndChangedRetryConflictsWithoutRewrite()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#pendingBindingAndOwnerRowsRollBackTogether()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#concurrentExactClaimsConvergeOnOneImmutableBinding()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#concurrentDifferentRequestsCannotClaimTheSameCommitIdentity()' \ + --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#concurrentChangedInputForOneRequestIsRejectedWithoutExtraOwnerRows()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#partialUnknownOwnerResultKeepsApplicationSlotAndCannotCreateVisibilityFence()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#exactAppliedResultReplayIsImmutableBeforeAndAfterSlotRelease()' \ --require-case 'net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepositoryIntegrationTest#mixedFinalAbortPreservesPriorFenceAndOwnerEvidenceAndFencesDelayedAttempts()' \ diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index f55cf123b2..1611d45001 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all nine coordinator and nine selection PostgreSQL cases with zero skips. Selection passed; eight coordinator cases passed and the identical-concurrent-claim case failed on the separate commit-identity unique constraint. This is a real exact-retry race, not a flaky result or missing execution. The correction atomically handles both request and commit identity collisions before comparing the complete stored binding; two additional concurrent changed-request/changed-input cases preserve rejection and no-extra-owner-row proof. Their strict CI requirements are included, but corrected PostgreSQL execution remains open. The separate twelve-case World REGION storage proof and its isolated upgrade-fixture correction belong in the [World tracker](./world-runtime-and-movement.md#current-status). None of these components supplies authenticated creation-initiator, creator bootstrap, Account party/terms authority, complete release participants or runtime lifecycle readiness. + The selected-Draft candidate now includes V45, a lossless widening of `publish_attempt.request_digest` from 64 to 71 characters for the exact prefixed selection digest. A V44-to-V45 case retains pending, successful and failed attempts, including absent historical digests, then writes and independently reads an exact selected digest. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) executed all five publication transaction tests: three passed, but the two selected-Draft cases failed because the production attempt column could not store that digest. The same run executed 14 descriptor mTLS and eight descriptor PostgreSQL cases successfully; the nine coordinator and eight selection cases were not run after the earlier failure and have no raw proof. Corrected PostgreSQL execution remains required. V24 already provides workflow-ID capacity and is not changed. These internal mechanics do not enable public publication or supply missing authenticated owner/release producers. The authored-publication candidate adds an internal durable Draft coordinator and exact existing-Draft selection. The shared complete-input codec retains the canonical target, exact base, ordered full revisions and complete declared owner/aggregate/scope epochs. V42 retains immutable owner results, definitive final abort and synchronized visibility; a definitive mixed vector becomes failed nonpublication without rewriting outcomes or advancing the prior view. V43 retains the first selected synchronized commit; V44 additionally enforces one Version per canonical tenant/publication-request identity without discarding conflicting retained history. The request, Temporal envelope and attempt carry the complete original selection and use the server-resolved existing Version, not a newly allocated empty Version. Public publication denies before dispatch or mutation while the current Account actor/role/party/terms producer and authenticated owner freeze/materialization are missing. Internal selected pending execution also denies before incompatible legacy participant calls or export. Historical provable terminal readback remains separate and does not manufacture missing selection evidence. These components do not prove normal synchronized editor reads, authenticated owner commits or complete release publication. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) owns that contract. 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 e527819fe8..83dbc166fb 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all 28 selected World PostgreSQL cases without skips: graph eight and publication-fence eight passed; guarded REGION storage executed twelve with eleven passes and one isolated retained-upgrade fixture failure. That fixture constructed a raw intake repository inside the owner transaction, so the committed-read guard rejected it before the intended FROZEN assertion. It now uses the normal declared `NOT_SUPPORTED` read composition on a separate connection to the same retained schema, verifies the exact committed receipt and retains all unchanged-row and frozen-write rejection assertions. Production guards are unchanged. Corrected upgrade execution remains required. The other eleven REGION cases establish component atomicity, race, exact retry and negative storage proof, not authenticated `APPLIED`, normal synchronized reads, released topology or the Game Session lifecycle handoff. + The guarded REGION storage candidate adds V29 and an explicitly unwired owner-local service over the existing World tables. The complete immutable Draft input and source-qualified V27 association bind the transaction; it derives and compares both REGION aggregate and REGION_SUBTREE epochs, writes all selected existing region rows, advances their epochs and retains the full six-family graph and exact result together. A single-use transaction-specific OLD/NEW execution manifest narrows the V24 write denial only for those exact transitions; ordinary legacy writes remain denied. Durable replay verifies the complete retained result, and a late conflict must roll back content, epochs and history together. The default permission verifier denies before opening a transaction, and successful synthetic component storage reports only `STORED_PERMISSION_UNVERIFIED`, never authenticated `APPLIED`. The twelve new PostgreSQL definitions include races, rollback, changed-input and corrupt-result denial, freeze ordering, invalid-manifest denial and retained V28-to-V29 migration; all compile but skip locally without Docker, so their execution remains open. The corrected three-service full-check/JAR/schema/docs gate passes in 1m22s with World265 clean unit results; these remain component checks, not runtime activation. At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](https://github.com/benhook1013/FireMUD/actions/runs/37333148281) World Build and Test succeeded. Independently parsed raw XML proves all eight authored-graph and eight publication-fence cases executed with zero skips, failures or errors, including the six corrected graph fixtures. Runner checkout logs independently identify that exact source. Game Design's coordination and selection cases also passed, but Account failed three distinct assertions/fixture expectations; aggregate green is not claimed. This execution predates V29 guarded REGION storage and establishes neither its database proof nor authenticated commit authority, synchronized normal reads, released topology or the canonical Game Session instance-to-World run lifecycle handoff. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java index cc68df5fe5..1156e49ec0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; -import java.sql.SQLException; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; @@ -26,7 +25,6 @@ import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import org.jooq.DSLContext; import org.jooq.Record; -import org.jooq.exception.DataAccessException; import org.springframework.stereotype.Repository; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Isolation; @@ -77,37 +75,29 @@ public CommitSnapshot claim(DraftCommitBinding binding) { return snapshot(existing); } - int inserted; - try { - inserted = - dsl.execute( - "INSERT INTO " - + COMMIT_TABLE - + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " - + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " - + "source_provenance_kind, request_id, commit_id, base_commit_id, input_digest, " - + "binding_json, workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'QUEUED') " - + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id) DO NOTHING", - binding.target().canonicalTenantId(), - binding.target().canonicalVersionId(), - binding.target().gameDesignVersionRowId(), - binding.target().gameDesignVersionTenantKey(), - binding.target().sourceGameRowId(), - binding.target().sourceGameTenantKey(), - binding.target().sourceProvenanceKind(), - binding.requestId(), - binding.commitId(), - binding.baseCommitId(), - binding.digest(), - binding.canonicalJson()); - } catch (DataAccessException exception) { - if (isUniqueConstraintViolation(exception)) { - throw new DraftCommitIdentityConflictException( - "Draft commit request or commit identity is already bound to different input", - exception); - } - throw exception; - } + int inserted = + dsl.execute( + "INSERT INTO " + + COMMIT_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, request_id, commit_id, base_commit_id, input_digest, " + + "binding_json, workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'QUEUED') " + // Request and commit are independent immutable identities; suppress either unique + // collision in PostgreSQL so the transaction remains readable for exact readback. + + "ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.target().gameDesignVersionRowId(), + binding.target().gameDesignVersionTenantKey(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); if (inserted == 0) { CommitRecord concurrent = findCommit(binding, true); @@ -1223,18 +1213,6 @@ private static OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); } - private static boolean isUniqueConstraintViolation(Throwable failure) { - Throwable current = failure; - while (current != null) { - if (current instanceof SQLException sqlException - && "23505".equals(sqlException.getSQLState())) { - return true; - } - current = current.getCause(); - } - return false; - } - private String canonicalJson(Object value) { try { byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java index 0a16d60cca..6817e79993 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java @@ -160,6 +160,97 @@ void concurrentExactClaimsConvergeOnOneImmutableBinding() throws Exception { } } + @Test + void concurrentDifferentRequestsCannotClaimTheSameCommitIdentity() throws Exception { + TargetProof target = fixture.newTarget(); + UUID commitId = UUID.randomUUID(); + var firstBinding = binding(target, UUID.randomUUID(), commitId); + var secondBinding = binding(target, UUID.randomUUID(), commitId); + + ConcurrentClaims claims = concurrentlyClaim(firstBinding, secondBinding); + assertExactlyOneClaimSucceeded(claims); + DraftCommitBinding winningBinding = + claims.left().snapshot() == null ? secondBinding : firstBinding; + DraftCommitBinding rejectedBinding = + claims.left().snapshot() == null ? firstBinding : secondBinding; + + CommitSnapshot persisted = + fixture.coordinator().read(target, winningBinding.requestId()).orElseThrow(); + assertThat(persisted.binding().canonicalBytes()) + .containsExactly(winningBinding.canonicalBytes()); + assertThat(persisted.ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(fixture.coordinator().read(target, rejectedBinding.requestId())).isEmpty(); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("commit_id"), UUID.class).eq(commitId))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(winningBinding.requestId()))) + .isEqualTo(winningBinding.requiredOwners().size()); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(rejectedBinding.requestId()))) + .isZero(); + } + + @Test + void concurrentChangedInputForOneRequestIsRejectedWithoutExtraOwnerRows() throws Exception { + TargetProof target = fixture.newTarget(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + var firstBinding = binding(target, requestId, commitId); + var changedBinding = + DraftCommitBinding.create( + firstBinding.target(), + firstBinding.requestId(), + firstBinding.commitId(), + firstBinding.baseCommitId(), + List.of( + new RevisionPayload( + "0", + firstBinding.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "{\"room\":\"changed concurrent input\"}"), + firstBinding.revisions().get(1)), + firstBinding.affectedUnits()); + + ConcurrentClaims claims = concurrentlyClaim(firstBinding, changedBinding); + assertExactlyOneClaimSucceeded(claims); + DraftCommitBinding winningBinding = + claims.left().snapshot() == null ? changedBinding : firstBinding; + + CommitSnapshot persisted = fixture.coordinator().read(target, requestId).orElseThrow(); + assertThat(persisted.binding().canonicalBytes()) + .containsExactly(winningBinding.canonicalBytes()); + assertThat(persisted.ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(requestId))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(requestId))) + .isEqualTo(winningBinding.requiredOwners().size()); + } + @Test void partialUnknownOwnerResultKeepsApplicationSlotAndCannotCreateVisibilityFence() { TargetProof target = fixture.newTarget(); @@ -828,6 +919,51 @@ private static T inTransaction(Supplier work) { return fixture.ownerTransaction().execute(status -> work.get()); } + private static ConcurrentClaims concurrentlyClaim( + DraftCommitBinding leftBinding, DraftCommitBinding rightBinding) throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future left = + executor.submit( + () -> { + ready.countDown(); + await(start); + return claimAttempt(leftBinding); + }); + Future right = + executor.submit( + () -> { + ready.countDown(); + await(start); + return claimAttempt(rightBinding); + }); + await(ready); + start.countDown(); + return new ConcurrentClaims(left.get(20, TimeUnit.SECONDS), right.get(20, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + } + + private static ClaimAttempt claimAttempt(DraftCommitBinding binding) { + try { + return new ClaimAttempt(inTransaction(() -> fixture.coordinator().claim(binding)), null); + } catch (RuntimeException exception) { + return new ClaimAttempt(null, exception); + } + } + + private static void assertExactlyOneClaimSucceeded(ConcurrentClaims claims) { + assertThat(claims.left().snapshot() == null).isNotEqualTo(claims.right().snapshot() == null); + ClaimAttempt rejected = claims.left().snapshot() == null ? claims.left() : claims.right(); + ClaimAttempt succeeded = claims.left().snapshot() == null ? claims.right() : claims.left(); + assertThat(rejected.failure()) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThat(succeeded.failure()).isNull(); + } + private static void await(CountDownLatch latch) { try { if (!latch.await(10, TimeUnit.SECONDS)) { @@ -840,6 +976,10 @@ private static void await(CountDownLatch latch) { } } + private record ClaimAttempt(CommitSnapshot snapshot, RuntimeException failure) {} + + private record ConcurrentClaims(ClaimAttempt left, ClaimAttempt right) {} + private record Fixture( DSLContext dsl, TransactionTemplate ownerTransaction, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java index a2227098a6..3707d8a0f4 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -46,16 +46,20 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -550,14 +554,32 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw .migrate(); assertThat(retainedRows(retained, scopes.keySet().stream().toList())).isEqualTo(before); SingleConnectionDataSource dataSource = new SingleConnectionDataSource(connection, true); + DataSourceTransactionManager retainedManager = new DataSourceTransactionManager(dataSource); + DriverManagerDataSource committedReadDataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + committedReadDataSource.setSchema(schema); + // Match the normal repository proxy's NOT_SUPPORTED read boundary. A separate connection + // reads this exact schema's committed intake while the owner transaction is suspended. + TransactionInterceptor readTransactions = new TransactionInterceptor(); + readTransactions.setTransactionManager(retainedManager); + readTransactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + ProxyFactory intakeProxy = + new ProxyFactory( + new WorldAuthoredSourceIntakeRepository( + DSL.using(committedReadDataSource, SQLDialect.POSTGRES))); + intakeProxy.setProxyTargetClass(true); + intakeProxy.addAdvice(readTransactions); WorldAuthoredSourceIntakeRepository retainedIntake = - new WorldAuthoredSourceIntakeRepository(retained); + (WorldAuthoredSourceIntakeRepository) intakeProxy.getProxy(); + assertThat(retainedIntake.read(NAMESPACE, f.intake().intakeRequestId()).orElseThrow()) + .isEqualTo(f.intake()); WorldDesignPublicationFenceRepository retainedFence = new WorldDesignPublicationFenceRepository(retained, retainedIntake); WorldDraftRegionCommitService deniedFrozen = new WorldDraftRegionCommitService( new WorldDraftRegionCommitRepository(retained, retainedFence, mapper), - new DataSourceTransactionManager(dataSource), + retainedManager, plan -> {}); assertThatThrownBy( () -> deniedFrozen.store(plan(f, List.of(f.first()), 1, "must-remain-frozen"))) From add1a85e3374ef0cb93330e96ba76bf5aac526f5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:30:30 +1300 Subject: [PATCH 07/11] Record executed Account source-ordering and exact recovery proof --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 cf1c6442bc..3a0fe589f3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) Account Build and Test succeeded. Independently parsed raw XML proves all 43 required selections passed without skips, including each of the three corrected atomicity/retained-role methods exactly once. The complete captured suites are authorization fence11, retained-role/JOIN55, role journal4, issuer22 and tenant18: all110 executed cleanly. This supersedes the earlier three Account fixture/assertion failures below, not the missing authenticated acting-account, creator bootstrap, complete source participation or activation proof. World and Game Design exposed separate upgrade-fixture and concurrent-claim defects; aggregate green is not claimed. + At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](https://github.com/benhook1013/FireMUD/actions/runs/37333148281) independently verified runner checkout and raw XML establish actual PostgreSQL execution, not local skips. All eleven Draft authorization-fence methods and the V59 retained-history/multibyte source-key case passed. Three distinct Account methods failed: issuer and tenant atomicity-denial tests inspected Spring's wrapper message rather than the correct nested PostgreSQL trigger error, and a retained-role fixture expected a second source writer to bypass the new pending-source guard. The two tenant strict-step failures are the same method, not separate defects. The correction retains the guard, proves competing-request denial and original completion, then exact historical retry after a later legitimate source advance; corrected execution remains required. Game Design and World jobs passed, but Account and aggregate readiness are not green. No producer authentication, complete source participation or activation follows from these component results. The corrected composed Account/Game Design/World full-check, boot-JAR, World jOOQ generation, formatting, Checkstyle, SpotBugs, coverage, links and Markdown gate passes in 1m22s (141 tasks:33 executed,108 up-to-date). Parsed unit results are Account954, Game Design517 and World265 executed cleanly; Account's unchanged unit result was reused, while Game Design and World executed in the final gate. One Game Design MinIO case and all587 PostgreSQL cases (Account381/Game Design129/World77) skip locally. Two added Game Design unit methods prove the closed fresh-creation request/caller-context guards and stored request-digest tamper denial before owner access; they do not authenticate a creator or grant first-admin authority. Flyway sanity passes for twelve sets/191 files, and230 architecture-contract tests pass. Runtime, credential and ring-mount gates remain closed. From 7a9439a741519eb51466e9993e2e536fa0fe3eed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:39:48 +1300 Subject: [PATCH 08/11] Read back exact committed World region results without a writer claim --- .github/workflows/ci.yml | 1 + .../world-runtime-and-movement.md | 2 + .../WorldDraftRegionCommitRepository.java | 14 +++++ .../tenant/WorldDraftRegionCommitService.java | 15 +++++ ...ftRegionCommitPostgresIntegrationTest.java | 60 +++++++++++++++++++ .../WorldDraftRegionCommitRepositoryTest.java | 50 +++++++++++++++- .../WorldDraftRegionCommitServiceTest.java | 35 +++++++++++ 7 files changed, 176 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7eae02480a..6776937b67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2178,6 +2178,7 @@ jobs: --require-suite net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#twoRegionsAdvanceFourTuplesWithFullHistoryAndExactLostAckReplay()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#committedReadbackReturnsOriginalFrozenHistoryWithoutPermissionOrMutation()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#lastScopeConflictRollsBackEarlierRegionPayloadEpochsAndEntireHistory()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#disjointTupleCommitsSucceedFromTheSameRetainedBaseWithoutRebasing()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPostgresIntegrationTest#immutableFullInputRejectsChangedBaseOtherOwnerPayloadOrderAndTuples()' \ 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 83dbc166fb..ad7519fed1 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The unwired REGION component now also exposes independent committed readback of the exact retained full plan/result. It does not enter the writer, run a fresh permission check, claim the shared owner row or mutate content/epochs/history; both entry points reject an active caller transaction. Complete binding, source association, graph and result-byte validation are the same as historical replay. An absent row is unknown, never definitive abort/no-commit proof. The result remains `STORED_PERMISSION_UNVERIFIED`; no authenticated endpoint or `APPLIED` result is introduced. Focused unit and PostgreSQL definitions cover original readback after a later commit/freeze, unknown absence, changed/corrupt evidence rejection and unchanged owner rows. The new PostgreSQL case is required by strict CI; local Docker-free compilation/skips do not establish its execution. + At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all 28 selected World PostgreSQL cases without skips: graph eight and publication-fence eight passed; guarded REGION storage executed twelve with eleven passes and one isolated retained-upgrade fixture failure. That fixture constructed a raw intake repository inside the owner transaction, so the committed-read guard rejected it before the intended FROZEN assertion. It now uses the normal declared `NOT_SUPPORTED` read composition on a separate connection to the same retained schema, verifies the exact committed receipt and retains all unchanged-row and frozen-write rejection assertions. Production guards are unchanged. Corrected upgrade execution remains required. The other eleven REGION cases establish component atomicity, race, exact retry and negative storage proof, not authenticated `APPLIED`, normal synchronized reads, released topology or the Game Session lifecycle handoff. The guarded REGION storage candidate adds V29 and an explicitly unwired owner-local service over the existing World tables. The complete immutable Draft input and source-qualified V27 association bind the transaction; it derives and compares both REGION aggregate and REGION_SUBTREE epochs, writes all selected existing region rows, advances their epochs and retains the full six-family graph and exact result together. A single-use transaction-specific OLD/NEW execution manifest narrows the V24 write denial only for those exact transitions; ordinary legacy writes remain denied. Durable replay verifies the complete retained result, and a late conflict must roll back content, epochs and history together. The default permission verifier denies before opening a transaction, and successful synthetic component storage reports only `STORED_PERMISSION_UNVERIFIED`, never authenticated `APPLIED`. The twelve new PostgreSQL definitions include races, rollback, changed-input and corrupt-result denial, freeze ordering, invalid-manifest denial and retained V28-to-V29 migration; all compile but skip locally without Docker, so their execution remains open. The corrected three-service full-check/JAR/schema/docs gate passes in 1m22s with World265 clean unit results; these remain component checks, not runtime activation. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java index 6d6b471555..bf274ff1c1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; @@ -42,6 +43,19 @@ public WorldDraftRegionCommitRepository( stager = new WorldDraftRegionGraphStager(); } + /** + * Independently reads the exact committed storage evidence without claiming an owner lock or + * write permission. Absence is unknown, never proof of abort or that an operation cannot commit. + */ + public Optional readCommitted(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + } + WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { requireTransaction(); String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java index 10444a1bea..27b27d7721 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.util.Objects; +import java.util.Optional; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -60,4 +61,18 @@ public WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { verifier.verify(plan); return Objects.requireNonNull(transaction.execute(status -> repository.store(plan))); } + + /** + * Reads original committed storage evidence without invoking permission verification or a writer + * transaction. The result remains permission-unverified; absence is unknown rather than an abort + * or definitive no-commit outcome. + */ + public Optional readCommitted(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return repository.readCommitted(plan); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java index 3707d8a0f4..2af9707633 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -143,6 +143,34 @@ void twoRegionsAdvanceFourTuplesWithFullHistoryAndExactLostAckReplay() { assertThat(count("world_region_draft_execution_manifest")).isZero(); } + @Test + void committedReadbackReturnsOriginalFrozenHistoryWithoutPermissionOrMutation() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan original = plan(f, List.of(f.first(), f.second()), 0, "original"); + // The default verifier denies storage, but independent readback needs no fresh permission. + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + Map> absentState = regionOperationState(); + assertThat(readback.readCommitted(original)).isEmpty(); + assertThat(regionOperationState()).isEqualTo(absentState); + assertThatThrownBy(() -> ownerTransaction().execute(status -> readback.readCommitted(original))) + .hasMessageContaining("no active caller transaction"); + assertThat(regionOperationState()).isEqualTo(absentState); + WorldDraftRegionCommitEvidence first = component().store(original); + component().store(plan(f, List.of(f.first(), f.second()), 1, "later")); + freeze(f); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitEvidence retained = readback.readCommitted(original).orElseThrow(); + assertThat(retained.binding()).isEqualTo(original.binding()); + assertThat(retained.ownerBinding()).isEqualTo(original.ownerBinding()); + assertThat(retained.graphBytes()).containsExactly(first.graphBytes()); + assertThat(retained.resultBytes()).containsExactly(first.resultBytes()); + assertThat(retained.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(name(f.first())).startsWith("later-"); + assertEpochs(f, 2, 2); + assertThat(regionOperationState()).isEqualTo(beforeRead); + } + @Test void lastScopeConflictRollsBackEarlierRegionPayloadEpochsAndEntireHistory() { Fixture f = fixture(); @@ -407,6 +435,12 @@ void corruptCompleteResultIsRejectedOnExactReplayWithoutRewritingContent() { }); assertThatThrownBy(() -> component().store(plan)) .hasMessageContaining("immutable result differs"); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> readback.readCommitted(plan)) + .hasMessageContaining("immutable result differs"); + assertThat(regionOperationState()).isEqualTo(beforeRead); assertEpochs(f, 1, 1); assertThat(name(f.first())).startsWith("retained-"); } @@ -609,6 +643,26 @@ private Map> retainedRows(DSLContext retained, List return rows; } + private Map> regionOperationState() { + return retainedRows( + dsl, + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_region_draft_commit", + "world_region_draft_execution_manifest", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_owner", + "world_design_publication_fence_attempt")); + } + private void race(Fixture f, long epoch) throws Exception { CountDownLatch begin = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); @@ -649,6 +703,12 @@ private void assertChanged( prior.target(), prior.requestId(), prior.commitId(), base, revisions, units), original.ownerBinding()); assertThatThrownBy(() -> component().store(changed)).hasMessageContaining("changed full input"); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> readback.readCommitted(changed)) + .hasMessageContaining("changed full input"); + assertThat(regionOperationState()).isEqualTo(beforeRead); } private WorldDraftRegionCommitPlan plan(Fixture f, List regions, long epoch, String name) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java index 91c2f15949..478cc91384 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java @@ -1,13 +1,25 @@ package net.firedevops.firemud.worldmanagement.tenant; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import java.sql.Connection; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.ResultQuery; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @@ -15,8 +27,9 @@ class WorldDraftRegionCommitRepositoryTest { private final DSLContext dsl = mock(DSLContext.class); private final WorldDesignPublicationFenceRepository fence = mock(WorldDesignPublicationFenceRepository.class); + private final ObjectMapper mapper = mock(ObjectMapper.class); private final WorldDraftRegionCommitRepository repository = - new WorldDraftRegionCommitRepository(dsl, fence, new ObjectMapper()); + new WorldDraftRegionCommitRepository(dsl, fence, mapper); private final WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); @AfterEach @@ -51,4 +64,39 @@ void repeatableReadCannotUseReadCommittedReplayAndOwnerLockOrdering() { .hasMessageContaining("writable READ COMMITTED"); verifyNoInteractions(dsl, fence, plan); } + + @Test + void committedReadbackRejectsActiveCallerBeforeStorageOrSourceResolution() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(dsl, fence, mapper, plan); + } + + @Test + @SuppressWarnings("unchecked") + void missingCommittedOperationIsUnknownWithoutOwnerClaimOrMutation() { + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + ResultQuery query = mock(ResultQuery.class); + Result rows = mock(Result.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(binding.requestId()).thenReturn(UUID.randomUUID()); + when(binding.commitId()).thenReturn(UUID.randomUUID()); + when(mapper.writeValueAsString(owner)).thenReturn("synthetic-owner-json"); + when(dsl.resultQuery(anyString(), any(Object[].class))).thenReturn(query); + when(query.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + assertThat(repository.readCommitted(plan)).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl).resultQuery(sql.capture(), any(Object[].class)); + assertThat(sql.getValue()) + .startsWith("SELECT ") + .doesNotContain("FOR UPDATE", "INSERT ", "UPDATE ", "DELETE "); + verify(query).fetch(); + verifyNoMoreInteractions(dsl, query); + verifyNoInteractions(fence); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java index 755eb72fd6..64de374f9a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java @@ -5,9 +5,12 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -83,4 +86,36 @@ void localFailureRollsBackWithoutReturningStorageEvidence() { order.verify(repository).store(plan); order.verify(manager).rollback(status); } + + @Test + void committedReadbackReturnsOriginalEvidenceWithoutVerifierOrTransactionInteractions() { + WorldDraftRegionCommitEvidence evidence = mock(WorldDraftRegionCommitEvidence.class); + when(repository.readCommitted(plan)).thenReturn(Optional.of(evidence)); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThat(service.readCommitted(plan)).containsSame(evidence); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void missingCommittedReadbackRemainsUnknownWithoutAttemptingDeniedWriter() { + when(repository.readCommitted(plan)).thenReturn(Optional.empty()); + WorldDraftRegionCommitService service = new WorldDraftRegionCommitService(repository, manager); + assertThat(service.readCommitted(plan)).isEmpty(); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeAnyCollaboratorInteraction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(repository, verifier, manager, plan); + } } From 968fa3bb98efa19f50e659f4769fc3b1537e0787 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:58:00 +1300 Subject: [PATCH 09/11] Observe real Account OTP transaction locks and record executed owner proof --- ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 + .../world-runtime-and-movement.md | 2 + ...ountAuthenticationUuidIntegrationTest.java | 61 ++++++++++++++++--- 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 1611d45001..7a828b0589 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Game Design Build and Test succeeded. Independently parsed raw XML proves all twenty required PostgreSQL cases executed once with zero skips, failures or errors: eleven coordinator and nine selection cases. This includes the repaired identical-concurrent claim and both conflicting concurrent-identity cases. The five publication transaction, eight descriptor PostgreSQL and fourteen physical mTLS cases also executed cleanly. Runner checkout `a4c1a66b3930de6825542b9b5a2e79410a067a65` has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the coordinator race and selected-Draft database fixture/proof gaps below; it does not supply the missing authenticated actor/owner/release producers or runtime activation. World passed its separate twenty-eight required cases; Account stopped at an inherited OTP transaction-observer fixture before its required source-proof cases executed. Aggregate green is not claimed. + At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all nine coordinator and nine selection PostgreSQL cases with zero skips. Selection passed; eight coordinator cases passed and the identical-concurrent-claim case failed on the separate commit-identity unique constraint. This is a real exact-retry race, not a flaky result or missing execution. The correction atomically handles both request and commit identity collisions before comparing the complete stored binding; two additional concurrent changed-request/changed-input cases preserve rejection and no-extra-owner-row proof. Their strict CI requirements are included, but corrected PostgreSQL execution remains open. The separate twelve-case World REGION storage proof and its isolated upgrade-fixture correction belong in the [World tracker](./world-runtime-and-movement.md#current-status). None of these components supplies authenticated creation-initiator, creator bootstrap, Account party/terms authority, complete release participants or runtime lifecycle readiness. The selected-Draft candidate now includes V45, a lossless widening of `publish_attempt.request_digest` from 64 to 71 characters for the exact prefixed selection digest. A V44-to-V45 case retains pending, successful and failed attempts, including absent historical digests, then writes and independently reads an exact selected digest. At source `8568f5c697a43eb98a251b4df8ab9f464ad38433`, [CI37320594491](https://github.com/benhook1013/FireMUD/actions/runs/37320594491) executed all five publication transaction tests: three passed, but the two selected-Draft cases failed because the production attempt column could not store that digest. The same run executed 14 descriptor mTLS and eight descriptor PostgreSQL cases successfully; the nine coordinator and eight selection cases were not run after the earlier failure and have no raw proof. Corrected PostgreSQL execution remains required. V24 already provides workflow-ID capacity and is not changed. These internal mechanics do not enable public publication or supply missing authenticated owner/release producers. 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 3a0fe589f3..1237cb8d74 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Account's preceding UUID/OTP integration selector failed in `emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce`: the transaction-observer fixture unwrapped a Mockito/Spring proxy and executed the real advisory-lock method while stubbing remained unfinished. Strict verifiers report all forty-three later required Account source cases missing with zero executions, not passing or skipped. The corrected fixture observes actual advisory-lock SQL through a restored-per-test jOOQ listener, asserts an active owner transaction at execution and requires an increasing observed-lock count for OTP request, verification, rejection, retry and rollback paths. Password-only paths are not required to take an OTP lock. Production authentication, consumption and transaction guards are unchanged. Local compilation without Docker does not prove this instrumentation runs; corrected PostgreSQL/Redis execution remains required. The earlier exact-source Account proof below remains valid at its own source, while Game Design and World passed their separately selected database proof at this newer head. No aggregate-green or activation claim follows. + At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) Account Build and Test succeeded. Independently parsed raw XML proves all 43 required selections passed without skips, including each of the three corrected atomicity/retained-role methods exactly once. The complete captured suites are authorization fence11, retained-role/JOIN55, role journal4, issuer22 and tenant18: all110 executed cleanly. This supersedes the earlier three Account fixture/assertion failures below, not the missing authenticated acting-account, creator bootstrap, complete source participation or activation proof. World and Game Design exposed separate upgrade-fixture and concurrent-claim defects; aggregate green is not claimed. At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](https://github.com/benhook1013/FireMUD/actions/runs/37333148281) independently verified runner checkout and raw XML establish actual PostgreSQL execution, not local skips. All eleven Draft authorization-fence methods and the V59 retained-history/multibyte source-key case passed. Three distinct Account methods failed: issuer and tenant atomicity-denial tests inspected Spring's wrapper message rather than the correct nested PostgreSQL trigger error, and a retained-role fixture expected a second source writer to bypass the new pending-source guard. The two tenant strict-step failures are the same method, not separate defects. The correction retains the guard, proves competing-request denial and original completion, then exact historical retry after a later legitimate source advance; corrected execution remains required. Game Design and World jobs passed, but Account and aggregate readiness are not green. No producer authentication, complete source participation or activation follows from these component results. 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 ad7519fed1..60f9617175 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) World Build and Test succeeded. Independently parsed raw XML proves all twenty-eight required PostgreSQL cases executed once with zero skips, failures or errors: graph eight, publication-fence eight and guarded REGION storage twelve. This includes the repaired retained V28-to-V29 upgrade case with the normal committed-read transaction composition and unchanged-row/frozen-write assertions. The runner merge has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the upgrade fixture proof gap below, not authenticated `APPLIED`, complete fresh topology, synchronized reads, released topology or the Game Session lifecycle handoff. The independent readback extension described next is later work and still requires its own execution. + The unwired REGION component now also exposes independent committed readback of the exact retained full plan/result. It does not enter the writer, run a fresh permission check, claim the shared owner row or mutate content/epochs/history; both entry points reject an active caller transaction. Complete binding, source association, graph and result-byte validation are the same as historical replay. An absent row is unknown, never definitive abort/no-commit proof. The result remains `STORED_PERMISSION_UNVERIFIED`; no authenticated endpoint or `APPLIED` result is introduced. Focused unit and PostgreSQL definitions cover original readback after a later commit/freeze, unknown absence, changed/corrupt evidence rejection and unchanged owner rows. The new PostgreSQL case is required by strict CI; local Docker-free compilation/skips do not establish its execution. At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all 28 selected World PostgreSQL cases without skips: graph eight and publication-fence eight passed; guarded REGION storage executed twelve with eleven passes and one isolated retained-upgrade fixture failure. That fixture constructed a raw intake repository inside the owner transaction, so the committed-read guard rejected it before the intended FROZEN assertion. It now uses the normal declared `NOT_SUPPORTED` read composition on a separate connection to the same retained schema, verifies the exact committed receipt and retains all unchanged-row and frozen-write rejection assertions. Production guards are unchanged. Corrected upgrade execution remains required. The other eleven REGION cases establish component atomicity, race, exact retry and negative storage proof, not authenticated `APPLIED`, normal synchronized reads, released topology or the Game Session lifecycle handoff. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 4a33c39fd8..95fcf08ef6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -7,10 +7,12 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.AccountServiceApplication; @@ -34,6 +36,10 @@ import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListenerProvider; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -103,23 +109,38 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private JavaMailSender mailSender; @MockitoBean private NotificationService notificationService; @MockitoSpyBean private AccountEmailLoginChallengeRepository challengeRepositorySpy; + private ExecuteListenerProvider[] previousExecuteListenerProviders; + private final AtomicInteger observedChallengeLockExecutions = new AtomicInteger(); @BeforeEach void observeOwnerTransaction() { - AccountEmailLoginChallengeRepository challengeRepositoryTarget = - AopTestUtils.getUltimateTargetObject(challengeRepositorySpy); - doAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - invocation.callRealMethod(); - return null; - }) - .when(challengeRepositoryTarget) - .lockAccountChallenge(anyLong()); + observedChallengeLockExecutions.set(0); + var configuration = dsl.configuration(); + previousExecuteListenerProviders = configuration.executeListenerProviders(); + ExecuteListenerProvider[] providers = + Arrays.copyOf( + previousExecuteListenerProviders, previousExecuteListenerProviders.length + 1); + providers[previousExecuteListenerProviders.length] = + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + String sql = context.sql(); + if (sql != null && "select pg_advisory_xact_lock(?)".equalsIgnoreCase(sql.trim())) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + observedChallengeLockExecutions.incrementAndGet(); + } + } + }); + configuration.set(providers); } @AfterEach void clearCallerContext() { + if (previousExecuteListenerProviders != null) { + dsl.configuration().set(previousExecuteListenerProviders); + } SessionContext.clear(); } @@ -212,25 +233,31 @@ void emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce String deliveredCode = requestEmailLoginOtpAndCaptureCode(email); String wrongCode = wrongOtpCode(deliveredCode); + int wrongCodeLockCount = observedChallengeLockExecutions.get(); assertThatThrownBy(() -> accountService.verifyEmailLoginOtp(email, wrongCode)) .isInstanceOf(AuthenticationException.class) .hasMessage("Invalid credentials"); + assertChallengeLockObservedSince(wrongCodeLockCount); var challengeAfterWrongCode = challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); assertThat(challengeAfterWrongCode.getInvalidAttemptCount()).isEqualTo(1); assertThat(challengeAfterWrongCode.getCodeHash()).isNotEqualTo(deliveredCode); assertThat(accountUuidFor(persisted.getId())).isEqualTo(expectedAccountUuid); + int successfulVerificationLockCount = observedChallengeLockExecutions.get(); var result = accountService.verifyEmailLoginOtp(email, deliveredCode); + assertChallengeLockObservedSince(successfulVerificationLockCount); assertThat(jwtUtil.parseToken(result.authToken()).getPayload().getAudience()) .containsOnly("account-service"); assertAuthenticationAndPrivateLookup(persisted.getId(), expectedAccountUuid, result); assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())).isEmpty(); assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); + int consumedChallengeRetryLockCount = observedChallengeLockExecutions.get(); assertThatThrownBy(() -> accountService.verifyEmailLoginOtp(email, deliveredCode)) .isInstanceOf(AuthenticationException.class) .hasMessage("Invalid credentials"); + assertChallengeLockObservedSince(consumedChallengeRetryLockCount); assertThat(accountUuidFor(persisted.getId())).isEqualTo(expectedAccountUuid); assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); } @@ -241,7 +268,9 @@ void playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce( UUID expectedAccountUuid = persisted.getAccountUuid(); String deliveredCode = requestEmailLoginOtpAndCaptureCode(persisted.getEmail()); + int successfulBootstrapLockCount = observedChallengeLockExecutions.get(); var result = accountService.issuePlayerBootstrap(persisted.getEmail(), deliveredCode); + assertChallengeLockObservedSince(successfulBootstrapLockCount); assertThat(result.accountId()) .isEqualTo(expectedAccountUuid.toString()) @@ -258,10 +287,12 @@ void playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce( assertThat(sessionService.isAccountSessionActive(persisted.getId(), result.bootstrapToken())) .isTrue(); + int consumedChallengeRetryLockCount = observedChallengeLockExecutions.get(); assertThatThrownBy( () -> accountService.issuePlayerBootstrap(persisted.getEmail(), deliveredCode)) .isInstanceOf(AuthenticationException.class) .hasMessage("Invalid credentials"); + assertChallengeLockObservedSince(consumedChallengeRetryLockCount); assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())).isEmpty(); assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); assertThat(sessionService.isAccountSessionActive(persisted.getId(), result.bootstrapToken())) @@ -365,10 +396,12 @@ private void assertRejectedEmailOtpPersistsChallengeAttempt( var challengeBeforeWrongCode = challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + int rejectedOtpLockCount = observedChallengeLockExecutions.get(); assertThatThrownBy( () -> attemptEmailOtpAuthentication(entryPoint, persisted.getEmail(), wrongCode)) .isInstanceOf(AuthenticationException.class) .hasMessage("Invalid credentials"); + assertChallengeLockObservedSince(rejectedOtpLockCount); var challengeAfterWrongCode = challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); @@ -404,10 +437,12 @@ void nonAuthenticationSessionFailureRollsBackOtpConsumption() { org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + int rollbackOtpLockCount = observedChallengeLockExecutions.get(); assertThatThrownBy( () -> accountService.verifyEmailLoginOtp(persisted.getEmail(), deliveredCode)) .isInstanceOf(IllegalStateException.class) .hasMessage("simulated session storage failure"); + assertChallengeLockObservedSince(rollbackOtpLockCount); ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); org.mockito.Mockito.verify(sessionServiceTarget) @@ -654,7 +689,9 @@ private Account createVerifiedAccount(String prefix) { } private String requestEmailLoginOtpAndCaptureCode(String email) { + int requestLockCount = observedChallengeLockExecutions.get(); accountService.requestEmailLoginOtp(email); + assertChallengeLockObservedSince(requestLockCount); ArgumentCaptor mailCaptor = ArgumentCaptor.forClass(SimpleMailMessage.class); org.mockito.Mockito.verify(mailSender).send(mailCaptor.capture()); @@ -668,6 +705,10 @@ private String requestEmailLoginOtpAndCaptureCode(String email) { return codeMatcher.group(1); } + private void assertChallengeLockObservedSince(int previousExecutionCount) { + assertThat(observedChallengeLockExecutions.get()).isGreaterThan(previousExecutionCount); + } + private String wrongOtpCode(String deliveredCode) { return deliveredCode.equals("000000") ? "000001" : "000000"; } From 73bfc04c9353a25cf1ab4d41e8f7cf759e35e752 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:35:18 +1300 Subject: [PATCH 10/11] docs: record executed authored-publication recovery proof --- design/project-management/ai-observations.md | 5 +++++ .../game-authoring-publishing-and-activation.md | 2 ++ .../implementation-tracking/player-access-and-session.md | 2 ++ .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 4 files changed, 11 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 583ad1f706..b615429655 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -435,3 +435,8 @@ Entry format: - `2026-10-06`: A focused service test can build another service's dirty prerequisites - Context: a focused Game Design tenant-readback test selected the World service's `generateJooq` through Game Design's existing test dependency while a disjoint helper was still preparing World migration V29. The selected Game Design tests did not execute because the prerequisite parser failed. - Expected pattern: inspect cross-service test dependencies before treating a focused module command as isolated from an active helper. Serialize validation after the dependency's handoff, preserve the real prerequisite failure, and do not count unexecuted selected tests as proof. The repository's locked Gradle entrypoint does not remove task dependencies. + +- `2026-10-06`: Unwrapping a repository spy did not make transaction observation stable + - Context: the Account OTP fixture described on `2026-10-02` failed again in exact-source CI37341390296 after earlier successful executions. Its ultimate-target `doAnswer` setup ran the real advisory-lock query while Mockito stubbing remained unfinished; the later forty-three required source-proof cases did not execute. The exact proxy/instrumentation cause remains unproved, so the older unwrapping recommendation is not sufficient evidence of stable setup. + - Outcome: the corrected fixture observes actual advisory-lock SQL through a per-test restored jOOQ listener, asserts the owner transaction and requires a positive observed-execution delta for each tested OTP operation. Exact-source CI37344877274 Account job and its persisted-UUID authentication command/strict case verifier succeeded; no standalone UUID/OTP XML or per-case verifier log was captured. Independently parsed downstream source-proof XML records all 110 captured Account methods cleanly, including the forty-three required selections that had not executed in the failed run. + - Expected pattern: transaction observation must not invoke the operation during instrumentation setup or pass vacuously when no observation occurs. Preserve the real lock, mutation and rollback assertions; a prior green run or Docker-skipped local check does not establish recovery. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 7a828b0589..e2949fc508 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) Game Design Build and Test succeeded. Independently parsed raw XML repeats all twenty required PostgreSQL cases cleanly without skips: coordinator11 and selected-Draft9, including the exact concurrent-claim correction. Verified runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has the exact unchanged Account parent and candidate parents, with head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`. Account's required source selections and World29 also passed at this source; aggregate CI was still active at the scoped handoff. Missing authenticated actor/creator/terms, complete owner/release producers, synchronized normal reads and runtime activation remain independent obligations. + At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Game Design Build and Test succeeded. Independently parsed raw XML proves all twenty required PostgreSQL cases executed once with zero skips, failures or errors: eleven coordinator and nine selection cases. This includes the repaired identical-concurrent claim and both conflicting concurrent-identity cases. The five publication transaction, eight descriptor PostgreSQL and fourteen physical mTLS cases also executed cleanly. Runner checkout `a4c1a66b3930de6825542b9b5a2e79410a067a65` has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the coordinator race and selected-Draft database fixture/proof gaps below; it does not supply the missing authenticated actor/owner/release producers or runtime activation. World passed its separate twenty-eight required cases; Account stopped at an inherited OTP transaction-observer fixture before its required source-proof cases executed. Aggregate green is not claimed. At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) executed all nine coordinator and nine selection PostgreSQL cases with zero skips. Selection passed; eight coordinator cases passed and the identical-concurrent-claim case failed on the separate commit-identity unique constraint. This is a real exact-retry race, not a flaky result or missing execution. The correction atomically handles both request and commit identity collisions before comparing the complete stored binding; two additional concurrent changed-request/changed-input cases preserve rejection and no-extra-owner-row proof. Their strict CI requirements are included, but corrected PostgreSQL execution remains open. The separate twelve-case World REGION storage proof and its isolated upgrade-fixture correction belong in the [World tracker](./world-runtime-and-movement.md#current-status). None of these components supplies authenticated creation-initiator, creator bootstrap, Account party/terms authority, complete release participants or runtime lifecycle readiness. 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 1237cb8d74..162e8a069d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) Account Build and Test succeeded. Independently parsed raw XML proves all 110 captured Account PostgreSQL methods passed without skips, failures or errors: authorization fence11, JOIN55, role journal4, issuer22 and tenant18. The duplicate tenant artifact is one execution, not another eighteen cases. All forty-three required authored-Draft selections are present and clean: fence11, retained-role/journal19, issuer7 and tenant6. The persisted-UUID authentication step also succeeded; its committed command runs fourteen UUID/OTP methods and three public-boundary methods, then strictly requires every case without skips. No standalone UUID/OTP XML or per-case verifier log was captured, so that narrower attribution rests on the successful strict step, not raw XML. Verified runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has exact Account parent `1a3122769f1251e6773838fe140788d5dcf20f99` and candidate parents, with head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`. This closes the transaction-observer execution gap below. Game Design20 and World29 required database methods also passed; aggregate CI was still active at the scoped handoff, and authenticated actor/creator/terms, complete publication and runtime activation remain unproved. + At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Account's preceding UUID/OTP integration selector failed in `emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce`: the transaction-observer fixture unwrapped a Mockito/Spring proxy and executed the real advisory-lock method while stubbing remained unfinished. Strict verifiers report all forty-three later required Account source cases missing with zero executions, not passing or skipped. The corrected fixture observes actual advisory-lock SQL through a restored-per-test jOOQ listener, asserts an active owner transaction at execution and requires an increasing observed-lock count for OTP request, verification, rejection, retry and rollback paths. Password-only paths are not required to take an OTP lock. Production authentication, consumption and transaction guards are unchanged. Local compilation without Docker does not prove this instrumentation runs; corrected PostgreSQL/Redis execution remains required. The earlier exact-source Account proof below remains valid at its own source, while Game Design and World passed their separately selected database proof at this newer head. No aggregate-green or activation claim follows. At exact source `a3eb1f5c9b4e55e94397d58541150701fa120a1d`, [CI37338019892](https://github.com/benhook1013/FireMUD/actions/runs/37338019892) Account Build and Test succeeded. Independently parsed raw XML proves all 43 required selections passed without skips, including each of the three corrected atomicity/retained-role methods exactly once. The complete captured suites are authorization fence11, retained-role/JOIN55, role journal4, issuer22 and tenant18: all110 executed cleanly. This supersedes the earlier three Account fixture/assertion failures below, not the missing authenticated acting-account, creator bootstrap, complete source participation or activation proof. World and Game Design exposed separate upgrade-fixture and concurrent-claim defects; aggregate green is not claimed. 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 60f9617175..c88f8dccf1 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) World Build and Test succeeded. Independently parsed raw XML proves all twenty-nine required PostgreSQL methods executed once without skips, failures or errors: graph8, publication-fence8 and guarded REGION storage13. The new `committedReadbackReturnsOriginalFrozenHistoryWithoutPermissionOrMutation` case passed, closing the independent-readback execution gap below while preserving its unknown-absence and unverified-permission limits. Runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has the exact unchanged Account parent and candidate parents and head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`; REGION XML SHA-256 is `1dad91fd526143453b9fccdd64702196094dee7d3b0da844938b0875e03a8136`. Account and Game Design jobs also succeeded; aggregate CI was still active at the scoped handoff. This is no proof of complete fresh topology, authenticated `APPLIED`, synchronized reads, released topology, canonical lifecycle delivery or activation. + At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) World Build and Test succeeded. Independently parsed raw XML proves all twenty-eight required PostgreSQL cases executed once with zero skips, failures or errors: graph eight, publication-fence eight and guarded REGION storage twelve. This includes the repaired retained V28-to-V29 upgrade case with the normal committed-read transaction composition and unchanged-row/frozen-write assertions. The runner merge has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the upgrade fixture proof gap below, not authenticated `APPLIED`, complete fresh topology, synchronized reads, released topology or the Game Session lifecycle handoff. The independent readback extension described next is later work and still requires its own execution. The unwired REGION component now also exposes independent committed readback of the exact retained full plan/result. It does not enter the writer, run a fresh permission check, claim the shared owner row or mutate content/epochs/history; both entry points reject an active caller transaction. Complete binding, source association, graph and result-byte validation are the same as historical replay. An absent row is unknown, never definitive abort/no-commit proof. The result remains `STORED_PERMISSION_UNVERIFIED`; no authenticated endpoint or `APPLIED` result is introduced. Focused unit and PostgreSQL definitions cover original readback after a later commit/freeze, unknown absence, changed/corrupt evidence rejection and unchanged owner rows. The new PostgreSQL case is required by strict CI; local Docker-free compilation/skips do not establish its execution. From a67b503558ec96f8659660abc3cf8333069eb80a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:03:13 +1300 Subject: [PATCH 11/11] Propagate existing bounded-wire CI dependency and callback isolation fixes --- .github/workflows/ci.yml | 4 ++++ dev-tools/tests/test_hosted_websocket_playable_smoke.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6776937b67..7a5a265080 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -321,6 +321,10 @@ jobs: with: requirements: ${{ (needs.changes.outputs.lightweight_only == 'true' && needs.changes.outputs.design_docs_changed == 'true' && needs.changes.outputs.validation_python_changed != 'true') && 'yaml' || 'ci' }} + - name: 📦 Install bounded wire test dependencies + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + run: python3 -m pip install --disable-pip-version-check --require-hashes -r config/python/smoke-requirements.txt + - name: 📦 Install cloc if: ${{ needs.changes.outputs.lightweight_only != 'true' }} env: diff --git a/dev-tools/tests/test_hosted_websocket_playable_smoke.py b/dev-tools/tests/test_hosted_websocket_playable_smoke.py index 869420d960..7c9be90fb9 100644 --- a/dev-tools/tests/test_hosted_websocket_playable_smoke.py +++ b/dev-tools/tests/test_hosted_websocket_playable_smoke.py @@ -1056,7 +1056,7 @@ def test_connect_token_cookie_requires_full_protection_before_wss(self): MODULE.run_smoke( self.config(), http_request=http, - websocket_factory=lambda *args: socket_attempts.append(args), + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), ) self.assertEqual(socket_attempts, [])