diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 3745c959ad..b2969c2bb1 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -65,7 +65,11 @@ The owner-local foundation persists authored-world source operations and deliver The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V30 exact creation-operation persistence, the owner-local transaction producer and source readback, and the exact Account/Game Session peer receipt read RPC. Validation evidence and remaining gaps belong to the linked implementation tracker. No creator RPC or authenticated creator authority is wired, and no Account association, membership, JOIN, or runtime admission is enabled by this source. -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered, but the earliest full-version publication foundation denies fresh and PENDING publication before mutation at the shared command boundary because no production source creates a genuine version-to-Draft association. The public `PublishVersion` route and configured orchestrator use that guard without starting a new workflow; registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are non-ingress and reachable only through a package-private unit proof seam; reflective mechanics tests use a mocked `PublishedReleaseBundleService`, so they do not prove an owner-backed publication path. They do not establish production publication. The private mechanics retain the Game Design workload identity and exact owner digest request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for version rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). `UploadPluginBundle` now 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` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. 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 any creator mutation class. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and plugin publication workflow remain in the current proto/service path. `PublishVersion` carries the selected existing Version, expected state epoch, and synchronized commit request/commit/digest. Public and registered Temporal ingress deny fresh and PENDING full-version requests before mutation: current Account authorization, authenticated World owner-freeze production, and a production version-to-Draft association are unavailable. The orchestrator does not start a workflow, and activities propagate the refusal without writes or synthetic terminal outcomes. The legacy no-selection shape supports exact retained terminal replay only: FAILED returns its stored result, while SUCCEEDED requires exact immutable release readback. + +Selected source capture, staging, export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The selected path freezes an immutable asset-export candidate and validates its origin/snapshot integrity; the finalizer requires a captured publication operation and same-transaction terminal seal. These mechanics and their local readback proofs do not establish Account authority, a production World freeze, public capability, or reachable publication success. The four owner-to-owner digest handlers retain exact Game Design workload identity and tenant/scope/request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). Release storage retains canonical Version identity, an opaque owner reference, manifest schema, artifact digests, and exact persisted readback; those fields do not establish selected commit provenance or a public tenant projection. The canonical digest and candidate rules are owned by [Version Control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](asset-storage.md#asset-lifecycle-and-publish-workflow). + +`UploadPluginBundle` persists signed plugin bundles and one allowlisted `signerKeyId`, but not the complete target `verifiedSignatures[]` set or an append-only signature-evidence ledger. `PublishPluginVersion` exports version-scoped plugin assets and checks `abilitySchemaDigest` against the `AUTOMATION_SCRIPTING` aggregate participant digest; the target Game Logic-owned ability-schema attestation for the same base version remains absent. Design-time revoke transitions and publication-event reads are present, while broader activation-time alias/binding validation remains incomplete. Account currentness 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. The shared deny-only owner-proof boundary also refuses `POST /assets` with HTTP `503 Service Unavailable` and its stable structured owner-proof error before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` requests before a Version write. Reads and an exact same-state no-op remain available. These refusals do not implement Account authorization, the legal lifecycle transition matrix, release evidence, or retirement predicates; full-version fresh/PENDING denial and exact terminal replay retain their existing behavior. @@ -96,15 +100,19 @@ The current runtime therefore provides no cross-owner apply, replay, or partial- 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. -Fresh and PENDING full-version publication is denied before mutation regardless of Temporal configuration. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Private mechanics are not production publication proof. The guard does not establish Account authorization or a World Management publication freeze. Restart-independent Temporal durability, workflow metadata, a genuine version-to-Draft association, and the required owner evidence remain unavailable or unproved. +When Temporal is disabled or its beans are absent, `PublishVersion` has no synchronous full-version fallback. Fresh and PENDING full-version publication is denied before mutation regardless of Temporal configuration because the command boundary lacks a production version-to-Draft association; the selected public route also lacks current Account authorization and authenticated World owner-freeze evidence. The configured orchestrator does not start a workflow for these requests, and registered activities propagate the refusal without writes or synthetic terminal outcomes. The no-selection legacy shape permits only exact terminal replay: FAILED returns the stored attempt result and SUCCEEDED requires exact immutable release readback. Captured-operation mechanics remain non-ingress package-private conditional proof through a narrow unit-test seam, not evidence of authorization or reachable publication. Legacy replay establishes no Temporal restart durability, workflow run ID, or independent workflow status metadata. 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). +The published realm-policy owner read is present behind the default-off `firemud.game-design.published-realm-entry-policy-read.enabled` provider. This slice adds only the two `PublishedRealmEntryPolicyService` methods to the base and production bearer-exemption lists; each handler still requires the verified same-namespace Game Session mTLS identity before decoding or owner access. The provider remains nonactivating and does not supply production Account or World authority. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for the source capability and qualified proof status. + ## gRPC APIs - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision` – persists a version-scoped revision when no `worldDesignMutation` is supplied. Requests carrying a typed World Management mutation, including `WORLD_GENERATION_SUBTREE`, currently receive `FAILED_PRECONDITION` from the registered World Management ingress before the Game Design revision is saved. -- `PublishVersion` – denies fresh/PENDING full-version publication before mutation while no production version-to-Draft association source exists, and replays exact terminal outcomes. The configured Temporal orchestrator delegates to the same command guard without starting a new workflow; registered activities propagate the same refusal without writes or synthesizing a terminal publication outcome. +- `ResolvePublishedRealmEntryPolicy` – returns immutable Game Design policy and provenance for one exact canonical tenant/version and world/realm selector pair; it does not compose runtime catalog or admission state. +- `ListPublishedRealmEntryPolicies` – returns the complete bounded policy set and owner-bound count/digest for one exact canonical tenant/version; it does not activate runtime state. +- `PublishVersion` – carries the exact selected existing Version, expected state epoch, and synchronized commit request/commit/digest identity, but fails closed before reservation because current Account authorization and authenticated World owner-freeze evidence are unavailable. The shared command boundary also denies fresh/PENDING requests before mutation until a production Version-to-Draft association exists; configured Temporal ingress uses the same guard, while no-selection requests are limited to exact terminal replay. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `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. @@ -132,6 +140,34 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e These gRPC entries are the discoverability index for the control-plane contracts described in [Game Templates and Configuration Tools](game-templates.md) and related architecture docs. When request/response schemas evolve, the proto contract and those architecture sections must be updated in the same change so launch-resolution and template-phase semantics do not drift. +### Authored source genesis and deterministic replay + +Game Design records an explicit immutable empty genesis only as part of genuinely new Draft creation. A missing source row is never evidence of empty content. Retained Drafts require a separate audited, authoritative baseline bound to their exact owner target and retained content; unknown or contradictory legacy lineage remains denied. Genesis and retained enrollment are owner evidence, not caller declarations, and neither substitutes for the creator authorization or exact affected-owner fencing required by [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). + +The closed `game-design-draft-base-reference/v1` grammar admits exactly two forms in the immutable reviewed proposal's `baseCommitId`: `genesis:` for the genuinely new Draft's first authored base, or the exact canonical UUID of a retained authored commit. UUIDs are non-nil lower-case canonical text; other prefixes, opaque labels, missing values and ambiguous references deny. The genesis form names the separately persisted shared command/policy receipt, not an authored commit. It never populates actual `commitId`, `sourceCommitId` or `inheritedCommitId` UUID fields. + +Before accepting the reviewed proposal, Game Design resolves that exact reference against its own persisted canonical target and Draft. Genesis resolution proves the original shared receipt UUID, creation lineage, receipt kind and version, complete stored policy/command evidence and evidence digest. Authored-base resolution proves the exact retained synchronized commit, complete owner result and source evidence for that target. The complete resolved evidence and digest are frozen with the exact reviewed binding, base, complete diff and affected epochs; retry preserves them byte-for-byte. Wrong-Draft, unknown, mismatched or contradictory receipt, digest or retained commit fails before a new application. Retained Drafts do not acquire inferred empty genesis. A later synchronized change confined to disjoint scopes does not rewrite the reviewed base or itself create a conflict; freshness remains the complete affected-owner epoch check in ADR 0129, not equality with the latest visible commit. + +Effective command and policy source is reconstructed deterministically from that proved baseline and the canonical commit/revision order. Each typed upsert or explicit deletion names its stable authored key and preserves the original immutable base, complete diff, revision identity, input digest and affected scope epochs. An omitted row is not a deletion. Partial owner applications remain invisible; only the exact fully synchronized owner fence advances the effective snapshot. Publication freezes the complete effective selected snapshot under the same owner serialization boundary, rather than selecting mutable latest rows or treating the last commit's diff as the full source. Exact retry and readback preserve the original source and capture bytes. No source enrollment or capture grants publication, launch or gameplay authority. + +### Published realm-entry policy owner read + +Game Design owns typed `REALM_ENTRY_POLICY` source and immutable published policy evidence. The policy data is one closed v1 JSON object with exactly `schemaVersion`, `worldSlug`, `worldDisplayName`, `realmSlug`, `realmDisplayName`, `visible`, `publicProduction`, `stateScope`, and `entryPolicy`. The schema version is integer `1`; all fields are required and typed, without boolean defaults. Slugs are canonical lower-case ASCII selectors of at most 64 characters; display names are trimmed, control-free text of at most 128 Unicode code points. The UTF-8 policy document is bounded to 4096 bytes. Unknown or duplicate JSON fields, malformed values, and unsupported policies deny. V1 supports only `entryPolicy=PRESEEDED_ONLY` with `stateScope=SHARED|ISOLATED`; descriptor and template fields do not belong to this policy. + +The [durable Draft coordinator](./version-control.md#design-time-synchronization) owns application and visibility. Source changes bind the complete canonical target, original authored revision and logical identity, exact input/commit digest, and affected policy scope epoch. A selected commit's diff is not the complete effective policy set: Game Design retains the complete synchronized effective snapshot, including unchanged policy provenance inherited from earlier owner applications. Partial owner writes remain invisible. A missing or contradictory owner baseline is denied, not reconstructed from the latest mutable revision, missing rows, slugs or numeric equality. Retained history never acquires inferred source authority. + +The existing closed UPSERT owner envelope is `{"revisionKind":"REALM_ENTRY_POLICY","logicalRevisionId":...,"policy":...}`. Explicit deletion uses exactly `{"revisionKind":"REALM_ENTRY_POLICY","logicalRevisionId":...,"operation":"DELETE","worldSlug":...,"realmSlug":...}` with canonical selectors. Mutations apply in canonical revision order; deletion rejects an absent `(worldSlug, realmSlug)` selector or a `logicalRevisionId` that does not match that effective policy, and removes only that exact selector. Omission is not deletion. Tenant/version-wide `realmSlug` uniqueness is checked on the final effective set, so a commit may delete a realm from one world and explicitly upsert it in another. + +Command-source mutations also apply in canonical revision order, and explicit deletion rejects a stable command key absent from the effective command set. + +Publication freezes that exact selected synchronized source and the complete original publication operation once. Source mutation and freeze share the owning Version serialization boundary. The effective published set has at most 128 policies, unique `(worldSlug, realmSlug)` selectors, tenant/version-wide `realmSlug` uniqueness, and exactly one `visible=true && publicProduction=true` policy. Game Design persists separate immutable policy rows and allocates each policy UUID once. Exact retry returns the original identities and bytes; conflicting evidence cannot silently select another source or bundle. Policy evidence binds canonical tenant/version and owner provenance, original source commit/revision/logical identity, the selected source capture, and the genuine sealed publication's workflow, manifest and release-content identity/digest. A source capture alone is not `PUBLISHED`. These separate rows and digests do not rewrite the closed release, terminal, launch-descriptor or release-attestation bytes. + +`ResolvePublishedRealmEntryPolicy` proves one exact selector; `ListPublishedRealmEntryPolicies` proves the complete ordered set, exact count and set digest. Both authenticate the same-namespace Game Session workload before decoding or owner access, independently read the exact canonical owner target and its full Version in `PUBLISHED` or `ACTIVE`, and verify the frozen source against the actual sealed publication and immutable release. Missing, contradictory, wrong-operation or mismatched digest evidence denies the complete response. No policy is inferred from a bundle, current mutable revisions or a caller's publication claim. The set read is complete-or-error: a bounded read detects an oversized set instead of returning a truncated prefix, and individual-selector proof cannot substitute for complete-set cardinality. Private owner row keys remain provenance, not public tenant/version identity. + +The [published-policy read proto](../../../../protos/game-design/v1/published_realm_entry_policy_service.proto) owns the closed schema-1 wire shape. Each read binds the configured namespace, a distinct non-nil canonical read-request UUID and canonical tenant/Version UUIDs; Resolve additionally binds the exact world and realm selectors. The response echoes that complete read request and carries the complete canonical `game-design-published-realm-policy-evidence/v1` set, not a selector-only fragment. This separate carrier retains the original operation, captured selected source and PUBLISHED terminal bytes, actual immutable release reference/content digest, workflow, manifest and original publication epoch, together with the ordered policy identities, source provenance, count and policy/set digests. It does not extend the closed release or terminal representation. Receivers authenticate Game Design, reject unknown fields, unsupported schemas or changed echoes, and verify every original evidence binding and digest before consuming content; digest integrity alone is not workload authentication. + +Published policy evidence alone establishes no runtime catalog, realm UUID, pointer, namespace resolution, lifecycle readiness, Entity assignment or admission. Game Session remains the runtime catalog owner and must compose the policy with its other owner evidence. Missing policy evidence denies that intake without enabling a fallback; [implementation status and proof](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) remain separate from this target contract. + ## REST & gRPC Endpoints Default ports: REST on `8080`, gRPC on `6565`. @@ -158,7 +194,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `AuthoredWorldVersionStateService.GetAuthoredWorldVersionState` (adapter `AuthoredWorldVersionStateGrpcService`) – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. - `AuthoredWorldSourceReadService.ResolveAuthoredWorldSource` (adapter `AuthoredWorldSourceReadGrpcService`) – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change when the request omits `worldDesignMutation`; carrying that optional typed mutation currently fails at the registered World Management ingress before the Game Design revision is saved. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes the exact selected frozen version. A new request carries stable `publish_request_id`, canonical selected `version_id`, `expected_version_state_epoch`, `selected_commit_request_id`, `selected_commit_id`, and `selected_commit_digest`; the complete synchronized commit is captured before source material is frozen. The request ID binds exact terminal replay, and the target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from it. Current public and registered Temporal paths fail closed for fresh and `PENDING` requests until genuine Account authorization and authenticated owner-freeze production are available; they do not start publication mechanics. The legacy no-selection request shape is limited to exact retained terminal replay and cannot authorize a new or pending publication. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. Timeout or failure remains explicit and may be outcome-pending until durable readback resolves it; no half-complete success is exposed. Retrying the same request must preserve its original selection and captured source bytes. The current boundary does not prove reachable live publication success. - `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)`. @@ -188,6 +224,9 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetVersionAssetPurgeStatus(GetVersionAssetPurgeStatusRequest) returns (GetVersionAssetPurgeStatusResponse)` – live operator-visible read of in-flight or failed purge workflow status; the target operation-ledger replay and reconciliation boundary remains incomplete. - `RepairPublishedVersionAssets(RepairPublishedVersionAssetsRequest) returns (RepairPublishedVersionAssetsResponse)` – live exact-bytes repair endpoint; it checks the durable source snapshot and candidate against the release attestation before writes. Source-byte immutability and physical database/object-store proof remain absent. +- `ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) returns (ResolvePublishedRealmEntryPolicyResponse)` – returns immutable Game Design policy and provenance evidence for the exact canonical tenant UUID, published version, and world/realm selector pair. It requires the exact `PUBLISHED` or `ACTIVE` full version and release bundle; a missing policy never falls back to legacy bundle or mutable revision data. +- `ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) returns (ListPublishedRealmEntryPoliciesResponse)` – returns the complete bounded frozen policy set and owner-bound count/digest for one canonical tenant UUID and exact published version; no pagination, truncation, legacy fallback, or partial success. + #### `AppendPluginVersionSignatureEvidence` (target only) This target mutation belongs to Game Design and is separate from runtime plugin activation. It is a signed-intake-only supplement to `UploadPluginBundle`: the target row must have entered the lifecycle through the allowlisted Ed25519 signed-intake path, and an unsigned package cannot use this RPC to manufacture signature evidence. Unsigned operator-permitted intake, when implemented under ADR 0111, needs its own platform-acceptance/approval evidence path and is not represented by this signature ledger. For signed intake, the mutation appends to an immutable evidence ledger; it never rewrites the uploaded bundle, signed payload, `pluginVersionId`, `bundleDigest`, publication status, or publication content. It is allowed only while the design-time status is `SIGNATURE_VERIFIED` or `PUBLISHED`; other statuses fail deterministically without mutation. A successful append on a `PUBLISHED` version does not republish or change its status, and an append on `SIGNATURE_VERIFIED` leaves that status unchanged. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 13a6eb08db..8074e3693e 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -20,6 +20,8 @@ V26's participant-scope and V27's effective-identity migrations are deliberately Current cross-seam security status is also blocked: Account's runtime membership and entitlement gRPC methods are configured as public-method bypasses and their handlers accept caller-supplied account/tenant identifiers without the target exact Game Session or World Management workload policy. Participant digest authorization and tenant-identity gaps are recorded below and remain unproved. +The current passive authored-publication prerequisite retains the first exact selection and does not release its reservation after definitive `FAILED`/`NO_PUBLICATION`. Fresh/PENDING registered ingress is denied before reservation; this containment does not establish failed-selection recovery. The authorized Game Design fresh-attempt or source-bound successor contract and proof remain an OPEN [production-readiness follow-up](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) before selected-publication enablement or genuine protected proof requiring recovery. Preserve immutable original evidence and fresh reviewed bindings; World’s ABORTED reopening after reconciled No Publication is a separate owner boundary. + ## Approach - Each asset revision already stores author and timestamp metadata. @@ -64,6 +66,10 @@ Game Design owns the durable, creator-visible coordination record for every shar - Game Design advances the synchronized fence only after every required owner durably reports the same exact commit and digest. Partial application remains diagnostic workflow state and cannot satisfy `IN_SYNC` or become a publish target. - Conflict assistance may construct a new proposed diff, but it must produce a new digest and exact base/epoch binding for creator review. Reconciliation never silently merges a stale proposal. +The [authored-source genesis and replay contract](./api-contracts.md#authored-source-genesis-and-deterministic-replay) requires explicit new-Draft genesis or an audited retained baseline before synchronized effective source can be captured. Its closed first-proposal base reference names the independently persisted genesis receipt, not a fabricated authored commit; subsequent authored bases name exact retained commit UUIDs. Proposal acceptance and frozen selection preserve the complete owner-resolved base evidence and digest rather than an opaque caller label. History and release assembly retain its stable-key replay and original source provenance; absent or unknown lineage cannot be normalized into empty content. + +Game Design's [realm-entry policy owner contract](./api-contracts.md#published-realm-entry-policy-owner-read) separately freezes the complete effective policy source at that selected synchronized fence. A latest mutable revision query or the selected commit's diff alone cannot supply unchanged inherited policy state. Policy capture and immutable published-policy association preserve the original operation and genuine terminal bundle without adding policy fields to the existing closed release or terminal representation; they do not establish runtime catalog or admission authority. + #### Publication freeze and owner handoff (Target State) The synchronized Draft fence is also the lifecycle handoff into publication. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. @@ -138,6 +144,8 @@ Game Logic's owner-local full-version manifest and provenance remain unproved. I Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. +For launch, attestation, and source-operation reads, workload authentication and request scope are necessary but not sufficient authorization. The read must also be bound to an authenticated, immutable receipt issued by the independently authorized owning operation: the receipt identifies the certificate-derived caller workload and namespace, canonical tenant, exact version and selected commit/digest, read purpose and scope, and the governing authorized operation/lifecycle. Caller-supplied tenant, correlation, or workload fields alone confer no authority. A valid receipt for an exact terminal read does not require that the version still have an active Draft. The binding preserves existing Account authorization and owner-source checks required by their contracts; exact terminal reads remain subject to the documented terminal-read policy and do not derive perpetual authority from a retained receipt. Operator diagnostics remain separately Account-authorized and do not gain launch or mutation authority through this binding. The receipt is evidence of the owning operation's existing authority, not a new revocation authority; this contract does not define a new receipt expiry or lifetime. + Current production behavior is narrower than this target: `GetPublishedReleaseBundle` authenticates only its exact candidate Game Session, World Management, or Automation & Scripting peer, while `GetVersionState` and `GetVersionAssetArtifactState` authenticate only their exact candidate Game Session or World Management peer; each then denies by default before owner reads pending genuine operation-specific authority. There is no current admin, generic internal-service, or bearer fallback, and the separate operator-diagnostic path above remains target-only and unimplemented. The isolated run-owned fixture's owner-local projection handoff does not change these production RPC permissions. Focused proof must cover each candidate peer and denied admin/internal/anonymous/wrong-namespace/wrong-peer calls, including that denied requests perform no owner read. In addition to domain-service digests, publish safety requires a Game Design control-plane digest: diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 6249dbbc7f..a43c074d23 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -24,7 +24,7 @@ The failed-candidate purge exception is target-only as well: Game Design must du The destructive asset lifecycle also remains target-only for operation durability: `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` must share the ADR 0048 owner-local operation envelope and result ledger (caller-stable operation/workflow identity, canonical `mutationDigest/v1`, exact replay, and `IDEMPOTENCY_CONFLICT` for changed input). The current first slice has no such shared ledger/digest contract, and `BeginPurgeVersionAssets` still mints a random workflow identity server-side. Artifact lifecycle saves now use a database epoch predicate and require one affected row, but Version lifecycle saves still lack that database compare-and-swap boundary and physical artifact CAS proof remains unavailable. An `expectedVersionStateEpoch` therefore cannot establish durable abandonment/retirement invalidation. -The live `CompareAndSetVersionState` path checks tenant/version scope and the expected epoch, preserves an exact same-state no-op, and refuses every state-changing request with `VERSION_STATE_MUTATION_UNAVAILABLE` before updating the Version. This deny-only boundary does not implement legal transitions, committed release bundle/artifact validation for `DRAFT -> PUBLISHED`, or retirement predicates for active instances, templates, and in-flight activation; the target transition authority and focused proof remain unavailable. +The live `CompareAndSetVersionState` path checks tenant/version scope and the expected epoch, preserves an exact same-state no-op, and refuses every state-changing request with `VERSION_STATE_MUTATION_UNAVAILABLE` before updating the Version. This deny-only boundary does not implement the [Game Design owner transition contract](./microservices/game-design-service/api-contracts.md#grpc-apis), legal transitions, committed release bundle/artifact validation for `DRAFT -> PUBLISHED`, database epoch-CAS proof, or retirement predicates for active instances, templates, and in-flight activation; state-changing transitions and focused activation/retirement proof remain unavailable. The private full-version publish failure path reads back release evidence and retains the Version rather than deleting it as compensation. Committed or partial bundle evidence and ambiguous failure-marking outcomes require reconciliation; only an exact absent-publication result can record definitive failure. This local implementation does not establish production full-version publication, and physical proof must still cover committed-bundle, absent-bundle, and ambiguous readback outcomes. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a05b93d5a4..240a291443 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -229,3 +229,9 @@ Entry format: - Context: the shared Gameplay observer monitored a large Validation matrix through `gh run view --json jobs`. - Observation: the returned jobs view omitted failed Buf and Game Logic rows. Their completion timestamps were 01:04:25 and 01:08:08 UTC, but the observer first discovered them around 01:16 UTC through the fully paginated Jobs API; the exact time the API exposed each failure was not recorded. This delayed front-PR failure reporting by roughly 12 and 8 minutes; no GitHub API or FireController failure was established. - Expected pattern: inspect the complete paginated source-run jobs inventory before metadata callbacks and report failed jobs while other jobs remain active. Do not wait for the whole workflow to finish or treat a partial jobs view as exhaustive. + +- `2026-10-13`: Focused validation must use declared test packages and enabled task flags + - Context: Gameplay’s #3120 review-fix prompts assumed that the `unit/` directory prefix was part of every Java package and omitted `-PfullCheck` from static-check tasks. + - Observation: the wrong class filter executed no tests and failed explicitly; the static tasks were reported `SKIPPED` despite a successful focused unit build. Neither result qualified the missing proof. + - Expected pattern: read the class’s declared package before specifying a test filter, and verify task execution rather than equating build success with every requested check passing. Enable the repository’s canonical full-check property when selecting static tasks. + - Current status: corrected package selection passed 50 focused unit cases; the subsequent runtime fix passed 58 selected unit cases. A separate canonical `-PfullCheck` run executed the required static checks successfully. No validation requirement was waived. 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 4f56846aa2..e051361f2f 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 @@ -8,12 +8,22 @@ This is a non-normative implementation tracker for game authoring, publishing, a At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. +The published #3120 immutable-source proof checkpoint is `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. This evidence is qualified to those postimages and is not a run on a later HEAD. + +The subsequent combined #3120 CLI5/Hosted3 fixes were validated locally before publication, based on `9bf78e22f742c3830821c920e70570eb1bc03e2b` plus develop `ee0c4c9545af05fa8d69644e78a99ea7c7031fe9`. The 2026-10-13 07:04–07:08 UTC full Game Design run executed 476 unit and 114 physical PostgreSQL cases with zero skips; one rollback assertion retained the old empty-table expectation despite the new legitimate baseline application. After correcting that assertion to prove the mutation row absent and the baseline retained, the 07:09–07:11 UTC affected 12-case PostgreSQL run passed with zero failures, errors or skips. Actual jOOQ generation, formatting, fullCheck, Checkstyle and all three SpotBugs tasks passed. These results qualify the inspected local fix postimages, not a later candidate or packaged runtime; historical container endpoint failures remain unexplained. + +The subsequent CLI6/Hosted4 correction batch passed local proof on 2026-10-13: 483 unit cases and 114 physical PostgreSQL cases with zero failures, errors or skips, using the shared pinned PostgreSQL image. Selected successful publication replay accepts exact committed evidence after PUBLISHED, ACTIVE or RETIRED without publication writes; mismatched bundle, artifact, gate and recorded digest remain denied. The policy publication fixture exercises the latest schema and exact authored source base. Formatting, fullCheck, Checkstyle, all three SpotBugs tasks, link checking, Markdown lint and the 79-leaf capability-tracking check passed. These results qualify the inspected source postimages; rebuilt packaged runtime on this correction batch remains unrun. + This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. +### Immutable command and realm-policy source + +Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. The historical published source proof checkpoint is `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary proof log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` covers 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on the matching postimages; this is not a run on a later HEAD. The subsequent combined local proof described above covers the V50.15 required-owner guard and exact publication-terminal denial assertions. Current-head source Validation `38361682862` (job `115177242916`, tested merge `c86f319c6e205e3c3b6a84b3915f144261470394`) independently executed 476 unit and 114 physical PostgreSQL cases with zero failures, errors or skips on published `3e8126217206419bc379497988884739a8e1fda0`. Runtime-consumer composition and activation remain unproved. The published-policy provider stays default-off and nonactivating, and its fixtures do not establish production Account or World authority. + ### Fresh-tenant identity prerequisite The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. @@ -22,6 +32,8 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The current producer captures real committed release-bundle, artifact-state, and version-state projections with the registered source and verifies them before resolving the exact source-bound default-template descriptor. It commits the actual descriptor resolution, independently reads it with its real request/result digests, and rereads source and current owner snapshots before atomically publishing the complete immutable run/project receipt. The capability and receipt bind actual Game Session and World Management leaf certificates to the same CA. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). +The three production read RPCs retain method-specific same-namespace denial before owner access, containing the generic internal-bearer bypass without granting successful read or activation credit. Authorized tenant/scope-bound terminal reads remain unimplemented pending a genuine independently authorized operation-receipt producer, carrier, and verifier for the named Game Session and World Management callers and, for release-bundle reads, Automation & Scripting, as defined by [Version Control](../../architecture/microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state) and [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). The `artifact-read-bearer-trust` and `release-read-tenant-binding` findings remain accepted/open and PR-unassigned production-readiness obligations under the production-readiness-followup decision 1222; they are not fixes in this passive source cut. The Major `failed-selection-recovery` obligation is likewise OPEN and PR-unassigned in that production-readiness follow-up. Game Design retains its immutable first publication selection after definitive `FAILED`/`NO_PUBLICATION`; no authorized fresh-attempt or source-bound successor recovery is implemented or proved. Fresh/PENDING registered publication remains denied before reservation. Before enabling selected publication or claiming genuine protected proof that requires recovery, define and prove the Game Design recovery contract while retaining original selection/terminal evidence and fresh reviewed bindings. World’s accepted ABORTED reopening contract after reconciled No Publication does not itself implement this Game Design boundary. This tracker update changes neither the #3120 owned source nor production RPC denial, and grants no fix/activation credit or new front prerequisite. + Historical original-source compositional proof was accepted for the bounded World fixture-lifecycle correction at `f330c8721824d063a5eba09afd5388631ae184b9`. The unchanged Java/test/migration parcel at `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` has passing World socket (2), PostgreSQL (3), provider (5), lifecycle unit (22), Game Design production-read denial (4), and producer PostgreSQL (7) cases with no skips. Rebuilt Smoke run `38174536549`, job `114575566943`, tested merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`) after the certificate/configuration repair, passing WebSocket WORLDS/LOGIN/PLAY/LOOK/LOGOUT and Telnet WORLDS/LOGIN/PLAY/LOOK. Focused physical tests and inspected source establish authenticated prepare/activate, exact replay/reconstruction, identity denial, actual opaque reference, and zero denied production-read calls; Smoke corroborates the packaged positive path without individual RPC trace/counter assertions. Startup refusal was skipped; packaged process restart, later protected activation, and hold race/restart proof are not established by this evidence. Earlier private #3151 reconstruction checks are historical evidence for their respective pins only. An earlier Common Platform gate reported 393 passing tests; a later fresh Game Design gate reported 373 passing tests with 61 integration tests skipped; the then-current parent `aeee77d07aa2ec815954c9627308882016ecaf24` reported 305 passing and 52 skipped in 47 seconds. Those results did not validate the merged private asset composition or full runtime. The two World authenticated socket cases passed, while Docker-backed PostgreSQL cases skipped and rebuilt packaged Smoke/restart remained unrun. Historical source proof does not qualify this reconstructed head. The retained `NEW_GAME_ROW` outbox is not delivery or World intake proof, and genuine production producer handoffs remain open; broader capability ratings are unchanged. @@ -32,8 +44,11 @@ The published run-owned fixture successor in #3171 consolidated local affected-c Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. -AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses with a mocked release-bundle service; a historical post-merge gate included Game Design tests and conditional mechanics proof, but this is not production publication or activation proof. The private path uses immutable content-addressed keys with conditional writes and exact readback, while physical deletion is hard-disabled; current evidence does not establish the previously suspected mutable-key overwrite or active-export cleanup races. Cross-phase coordination and external-write recovery remain unproved. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Historical original-source fixture proof and current private local checks are recorded in [Run-owned authored-world fixture repair](#run-owned-authored-world-fixture-repair); neither establishes the broader physical publication boundary or validates this composition. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). -The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open `CompareAndSetVersionState` lifecycle transition gap recorded below; state-changing requests now fail closed pending owner proof, but the legal transition matrix and its focused proof remain absent. +AR-1.5 full-version publication remains fail-closed at public and registered Temporal ingress. The selected request carries an exact existing Version, expected state epoch, and synchronized commit identity, but current Account authorization, authenticated World owner-freeze production, and a production version-to-Draft association are unavailable. The shared command guard denies fresh and PENDING requests before mutation; the configured orchestrator does not start a workflow, and registered activities propagate the refusal without writes or synthetic terminal outcomes. Exact terminal replay remains available: FAILED returns its stored result, while SUCCEEDED requires exact immutable bundle readback. + +Selected source capture, candidate staging/export, finalization, and terminal sealing remain non-ingress package-private conditional mechanics, not production publication. The asset candidate retains its frozen origin and snapshot-integrity checks; the selected finalizer requires a captured publication operation and same-transaction terminal seal. The private asset path uses immutable content-addressed keys, conditional writes, and exact readback, while physical deletion is hard-disabled. Local transaction, participant, and ambiguous-readback proof does not establish authorization, a production World freeze, or a reachable success path. PostgreSQL rollback, physical object-store behavior, live Temporal-owner publication, cross-phase recovery, and historical revision/version lineage remain unproved. Current ingress status is owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); digest and candidate rules are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). + +The existing publication proof remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams; it does not prove a complete successful producer or end-to-end Temporal activity-to-owner path. V28 corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. Database rollback/ambiguous-commit recovery and live workload-certificate admission are likewise unproved. This migration correction is separate from the `CompareAndSetVersionState` transition gap: state-changing requests now fail closed pending owner proof, but the legal transition matrix remains absent. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves now include an epoch predicate and affected-row check; Version saves still lack a database epoch predicate and affected-row check, and physical database proof for artifact CAS is unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. @@ -68,7 +83,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | @@ -135,16 +150,15 @@ Built-in and authored commands use one provider-backed `TextCommandRegistry` and `TextCommandParser` carries canonical authored IDs into `TextCommandPayload.AuthoredActionInvocation` and resolves authored/extension command IDs even when alias metadata is absent. The authored dispatch handler fails closed on unknown authored action IDs. `HELP` discovery and direct lookup project authored topics from the admitted registry. The obsolete configuration-backed authored-action catalog, parser/help fallback, and test-profile registry fallback have been removed; the published release bundle is the only authored-command authority. -`COMMAND_DEFINITION` revisions accept the first typed schema, reject malformed metadata before persistence, and cannot change after version publication. Full-version publication snapshots ordered validated definitions into the immutable release bundle, and the Game Design control-plane digest changes when their command contract changes. Targeting, cost, and tick-relative cooldown metadata are validated and carried through the shared definition seam, while their general execution semantics remain future work beyond the release-admitted `APPLY_ACTION_STATE` v1 path. `APPLY_ACTION_STATE` v1 is validated at revision and publication time for self-targeting, effect-idempotent replay, bounded duration, and shared-effect-engine modifier grammar. The first live executor supports only release-admitted self-targeted `APPLY_ACTION_STATE` v1; malformed or unsupported effect snapshots and stale session identity fail closed before durable execution. Admission persists release-bundle and version IDs with the command, but durable execution does not yet revalidate those IDs against the currently running release. +`COMMAND_DEFINITION` revisions accept the first typed schema, reject malformed metadata before persistence, and cannot change after version publication. The selected full-version bundle path requires the immutable command source captured for the exact synchronized selection; its legacy five-argument entrypoint fails closed instead of rebuilding from mutable revision rows. The current public publication path cannot yet create a release because its Account authorization and authenticated owner-freeze producer are absent. Targeting, cost, and tick-relative cooldown metadata are validated and carried through the shared definition seam, while their general execution semantics remain future work beyond the release-admitted `APPLY_ACTION_STATE` v1 path. `APPLY_ACTION_STATE` v1 is validated at revision and publication time for self-targeting, effect-idempotent replay, bounded duration, and shared-effect-engine modifier grammar. The first live executor supports only release-admitted self-targeted `APPLY_ACTION_STATE` v1; malformed or unsupported effect snapshots and stale session identity fail closed before durable execution. Admission persists release-bundle and version IDs with the command, but durable execution does not yet revalidate those IDs against the currently running release. The broader authored-action model is not complete. The locked expansion boundary is one version-scoped typed definition seam with implicit `SOURCE` targets and bounded keyed `ActionTargetSet` declarations that reference release-pinned reusable `TargetSelectionPolicy` values. The remaining model distinguishes a reusable `TargetingPolicy` that returns eligible candidates from `TargetSelectionPolicy`, which supplies cardinality and typed selection strategy; target sets retain required/optional behavior and optional player-input slots. Future costs, tick-relative cooldowns, durations, ordered effect steps, and additional effect kinds must remain on the admitted definition snapshot and shared effect/timing boundary rather than per-command scripts or mutable runtime registry reads. ### Publication, Temporal Workflows, and Release Attestation -Asset lifecycle status and proof remain partial: the current source has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published exact-byte repair independently reads the candidate and checks it against the exact release bundle before object writes. The candidate/export/repair implementation is present, while integrated migration closure and focused physical database/object-store execution remain unproved. Destructive lifecycle operation safety, global publication/purge fencing, and runtime readiness remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records current status without repeating those owner contracts. +Asset lifecycle status and proof remain partial: durable `version_asset` mappings and a version-scoped export snapshot have independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published exact-byte repair independently reads the candidate and checks it against the exact release bundle before object writes; repair does not create a snapshot or candidate. Candidate origin and snapshot-integrity checks are present, while integrated migration closure and focused physical database/object-store execution remain unproved. Destructive lifecycle operation safety, global publication/purge fencing, restart recovery, and runtime readiness remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions). -Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. The same local deny-only owner-proof boundary now rejects `POST /assets` before multipart access or persistence and state-changing `CompareAndSetVersionState` calls before Version mutation; this does not establish Account authorization or lifecycle-transition safety. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. Historical original-source fixture proof and current private local checks are recorded in [Run-owned authored-world fixture repair](#run-owned-authored-world-fixture-repair); they do not establish production publication. An earlier consolidated local validation reported no Game Design unit-test failures or skips and passed integration-test source compilation, formatting, and documentation checks; these remain historical proof scopes, while physical database, object-store, and Temporal execution remain unproved. The donor tracker records exact foundation CI run 37872819991 as green for its original head; it is historical evidence and does not validate this composition. The publication guard does not establish a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. -The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. Public and registered Temporal ingress deny fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association. FAILED replay returns the stored result; SUCCEEDED replay requires exact immutable release readback. Source capture, candidate export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The candidate path retains its frozen origin and snapshot integrity, and the finalizer requires a captured operation and same-transaction terminal seal. The local owner-proof boundary rejects `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` before Version mutation; neither establishes Account authority or lifecycle-transition safety. Physical database, object-store, rollback, concurrent retry, committed/absent/ambiguous recovery, and live Temporal-owner execution remain unproved. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. Full-version publication also lacks Game Logic owner-local manifest/provenance for version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest, candidate, and asset lifecycle contracts are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The current release storage preserves canonical Version identity, an opaque reference, manifest schema, artifact digests, and exact persisted bundle readback; canonical target-commit provenance and a public tenant projection remain absent. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md). Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 05eba37107..f667aa3b22 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -88,6 +88,8 @@ The exact source-run publication handoff is implemented locally in the runtime p ## Operator Write Boundary Status +The StartSession prerequisite now includes the shared action/digest and pre-authorization tuple, Logging & Admin's durable reservation/claim/recovery seams, and Account's read-only current tenant-scoped control-ui actor verification. It does not issue or redeem operator references, forward owner mutations, or provide canonical Game Session execution. The [StartSession schema owner](../../architecture/microservices/game-session-service/start-session-action-schema.md#implementation-status) records this partial boundary; physical reservation/authority integration, owner handoff, and live launch proof remain open. + The tracker separates implemented fail-closed ingress stubs from supported durable operator workflows and the target external ingress contract. Game Session `/sessions*` routes remain internal/owner-local. Logging & Admin feature-flag and scoped tick ingress stubs remain externally unavailable because they do not currently forward and the complete [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) owner-write gate is not implemented or proved. Moderation and appeal implementation status remains owned by the [Logging & Admin moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md) contract; quota overrides, broader remediation, external session-lifecycle forwarding, and other unproved owner mutations remain gated or target-only. ## Canonical Design Sources diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 91483b3661..a9eac7b621 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -124,6 +124,16 @@ message PublishVersionRequest { string tenant_id = 1; string notes = 2; string publish_request_id = 3; + // Complete together for new publication: the exact existing Draft selection. When set, + // tenant_id, version_id, selected_commit_request_id, and selected_commit_id must be + // canonical lower-case non-nil UUIDs (tenant_id is the canonical tenant UUID, not the key). + // When all selection fields are empty, tenant_id is the legacy tenant key and only a + // retained terminal legacy retry is eligible. + 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/build.gradle.kts b/services/game-design-service/build.gradle.kts index afb84ecf30..f404aca6d2 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -26,4 +26,7 @@ testing { dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) + testImplementation(libs.bouncycastle.pkix) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java new file mode 100644 index 0000000000..24e65c58fd --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.gamedesign.config; + +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Explicit opt-in composition for the protected published realm-policy owner read. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-design.published-realm-entry-policy-read", + name = "enabled", + havingValue = "true") +public class RealmPolicyPublicationReadConfiguration { + + @Bean + RealmPolicyPublicationRepository realmPolicyPublicationRepository(DSLContext dsl) { + return new RealmPolicyPublicationRepository(dsl); + } + + @Bean + RealmPolicyPublicationService realmPolicyPublicationService( + RealmPolicyPublicationRepository repository, PlatformTransactionManager transactions) { + return new RealmPolicyPublicationService(repository, transactions); + } +} 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..94ec38dc56 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; + +/** + * Exact existing synchronized Draft selection. The shared codec preserves the original V43 bytes + * and digest; neither this retained selection nor codec validation establishes publication + * authority. + */ +public final class AuthoredDraftPublishSelection { + private final AuthoredDraftPublishSelectionBinding binding; + + private AuthoredDraftPublishSelection(AuthoredDraftPublishSelectionBinding binding) { + this.binding = Objects.requireNonNull(binding); + } + + public static AuthoredDraftPublishSelection capture( + PublishIntent intent, TargetProof target, PublicationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + var fence = evidence.visibilityFence(); + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.capture( + sharedIntent(intent), + target, + evidence.binding(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + fence.target(), + fence.requestId(), + fence.commitId(), + fence.inputDigest(), + fence.resultVectorJson(), + fence.createdAt()))); + } + + public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.fromStored(storedJson, storedDigest)); + } + + public PublishIntent intent() { + var intent = binding.intent(); + return new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + public TargetProof target() { + return binding.target(); + } + + public DraftCommitBinding selectedCommit() { + return binding.selectedCommit(); + } + + public UUID fenceRequestId() { + return binding.fenceRequestId(); + } + + public UUID fenceCommitId() { + return binding.fenceCommitId(); + } + + public String fenceInputDigest() { + return binding.fenceInputDigest(); + } + + public String fenceResultVectorJson() { + return binding.fenceResultVectorJson(); + } + + public String fenceCreatedAt() { + return binding.fenceCreatedAt(); + } + + public String canonicalJson() { + return binding.canonicalJson(); + } + + public byte[] canonicalBytes() { + return binding.canonicalBytes(); + } + + public String digest() { + return binding.digest(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelection selection + && binding.equals(selection.binding)); + } + + @Override + public int hashCode() { + return binding.hashCode(); + } + + private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent( + PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + return new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + /** Full original eight caller inputs, retaining the existing public API. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + new AuthoredDraftPublishSelectionBinding.PublishIntent( + canonicalTenantId, + canonicalVersionId, + publishRequestId, + expectedVersionStateEpoch, + notes, + selectedCommitRequestId, + selectedCommitId, + selectedCommitDigest); + } + } +} 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..31adbd248b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java @@ -0,0 +1,272 @@ +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"); + + 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); + 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 operation already reserves an exact 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 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) { + 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..7112d7a34d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -0,0 +1,1680 @@ +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.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.DraftAuthorizationFenceBinding; +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 net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +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; + private final GameDesignDraftTerminalOutcomeRepository terminalOutcomes; + + @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"); + this.terminalOutcomes = new GameDesignDraftTerminalOutcomeRepository(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 = + 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); + 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); + } + + /** + * Claims a complete Account operation alongside its coordinator binding before dispatch. The + * Account bytes are exact source material only; this storage operation does not authenticate them + * or authorize owner writes. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim( + DraftCommitBinding binding, DraftAuthorizationFenceBinding originalAccountBinding) { + requireWritableReadCommittedTransaction(); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(originalAccountBinding, binding); + LockedVersion lockedVersion = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + terminalOutcomes.validateClaim(operation, lockedVersion); + CommitSnapshot snapshot = claim(binding); + terminalOutcomes.claim(operation, lockedVersion); + return snapshot; + } + + /** 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()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + 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()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + 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 = CAST(? AS timestamptz) " + + "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()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + 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 = CAST(? AS timestamptz) " + + "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); + } + + /** + * Canonical source-aware fence handoff. The caller still supplies independently verified owner + * proof; both complete source snapshots become visible in this same owner transaction. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceSourceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + var sources = new GameDesignSourceRepository(dsl); + if (sources.readGenesis(binding.target()).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + VisibilityFence fence = advanceVisibilityFence(binding, coordinatorProof); + sources.captureSynchronized(binding); + return fence; + } + + /** + * Advances the internal synchronized visibility record only from the complete exact APPLIED + * result vector. This package-private 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) + VisibilityFence advanceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(coordinatorProof, "coordinatorProof"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + 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"); + } + terminalOutcomes.recordCommitted(binding, existing, resultVectorJson, false); + 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"); + } + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "A pre-existing visibility fence is not paired with synchronized workflow state"); + } + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, false); + 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); + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, true); + 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 (terminalOutcomes.isAccountBound(binding)) { + throw new DraftCommitStateConflictException( + "An Account-bound Draft commit requires its exact final-abort tombstone and complete owner vector"); + } + 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); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, existingAbort), + exactTerminalAbortResultVector(binding, lockAndReadOwnerStates(binding)), + false); + return toFinalAbortReceipt(binding, existingAbort); + } + + terminalOutcomes.requireNotDefinitivelyAborted(binding); + 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"); + } + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + false); + return toFinalAbortReceipt(binding, persisted); + } + + updateWorkflowState(binding, WorkflowState.FAILED_NONPUBLICATION); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + true); + 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 String exactTerminalAbortResultVector( + DraftCommitBinding binding, List ownerStates) { + requireCompleteTerminalAbortVector(binding, ownerStates); + List> resultVector = new ArrayList<>(); + 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")); + resultVector.add(ownerResultJson(state.outcome().orElseThrow())); + } + return canonicalJson(resultVector); + } + + 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 = CAST(? AS timestamptz) " + + "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_V29') " + + "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 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/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java new file mode 100644 index 0000000000..535f147e1d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** + * Exact Account operation material paired with the complete Game Design commit binding. + * + *

This value validates identity and canonical bytes only. It does not authenticate the Account + * source evidence or authorize a write; that decision belongs to the protected Account producer. + */ +public final class GameDesignDraftTerminalOperation { + private final DraftAuthorizationFenceBinding accountBinding; + private final DraftCommitBinding gameDesignBinding; + private final byte[] accountBindingBytes; + private final String accountBindingDigest; + + public GameDesignDraftTerminalOperation(DraftAuthorizationFenceBinding accountBinding) { + this(accountBinding, bindingFrom(accountBinding)); + } + + public GameDesignDraftTerminalOperation( + DraftAuthorizationFenceBinding accountBinding, DraftCommitBinding gameDesignBinding) { + this.accountBinding = Objects.requireNonNull(accountBinding, "accountBinding"); + this.gameDesignBinding = Objects.requireNonNull(gameDesignBinding, "gameDesignBinding"); + this.accountBindingBytes = accountBinding.canonicalBytes(); + this.accountBindingDigest = sha256(accountBindingBytes); + if (!Arrays.equals(accountBinding.gameDesignBinding(), gameDesignBinding.canonicalBytes()) + || !accountBinding.inputDigest().equals(gameDesignBinding.digest()) + || !accountBinding.requestId().equals(gameDesignBinding.requestId()) + || !accountBinding.commitId().equals(gameDesignBinding.commitId()) + || !accountBinding.tenantId().equals(gameDesignBinding.target().canonicalTenantId()) + || !accountBinding.versionId().equals(gameDesignBinding.target().canonicalVersionId()) + || !accountBinding.baseCommitId().equals(gameDesignBinding.baseCommitId())) { + throw new IllegalArgumentException( + "Account terminal operation differs from the exact complete Game Design binding"); + } + } + + public DraftAuthorizationFenceBinding accountBinding() { + return accountBinding; + } + + public DraftCommitBinding gameDesignBinding() { + return gameDesignBinding; + } + + public byte[] accountBindingBytes() { + return accountBindingBytes.clone(); + } + + public String accountBindingDigest() { + return accountBindingDigest; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOperation other) { + return other != null + && accountBindingDigest.equals(other.accountBindingDigest) + && Arrays.equals(accountBindingBytes, other.accountBindingBytes) + && gameDesignBinding.digest().equals(other.gameDesignBinding.digest()) + && Arrays.equals( + gameDesignBinding.canonicalBytes(), other.gameDesignBinding.canonicalBytes()); + } + + private static DraftCommitBinding bindingFrom(DraftAuthorizationFenceBinding accountBinding) { + Objects.requireNonNull(accountBinding, "accountBinding"); + return DraftCommitBinding.fromStored( + new String(accountBinding.gameDesignBinding(), StandardCharsets.UTF_8), + accountBinding.inputDigest()); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java new file mode 100644 index 0000000000..9e64a5488b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable final Game Design owner result for one exact Account operation. + * + *

A missing outcome is unresolved, never an abort. The retained owner vector is Game Design's + * internal participant evidence; it is not a substitute for Account's independent World outcome. + * This record is readback data, not an authorization decision or an authenticated RPC receipt. + */ +public final class GameDesignDraftTerminalOutcome { + private static final ObjectMapper JSON = new ObjectMapper(); + + public enum Result { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private final GameDesignDraftTerminalOperation operation; + private final Result result; + private final String ownerResultVectorJson; + private final byte[] finalEvidenceBytes; + private final String finalEvidenceDigest; + private final OffsetDateTime createdAt; + + GameDesignDraftTerminalOutcome( + GameDesignDraftTerminalOperation operation, + Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes, + String finalEvidenceDigest, + OffsetDateTime createdAt) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.result = Objects.requireNonNull(result, "result"); + this.ownerResultVectorJson = + Objects.requireNonNull(ownerResultVectorJson, "ownerResultVectorJson"); + if (ownerResultVectorJson.isBlank()) { + throw new IllegalArgumentException( + "A final outcome requires its complete owner result vector"); + } + validateOwnerResultVector(); + this.finalEvidenceBytes = + Objects.requireNonNull(finalEvidenceBytes, "finalEvidenceBytes").clone(); + if (this.finalEvidenceBytes.length == 0) { + throw new IllegalArgumentException("A final outcome requires exact terminal evidence bytes"); + } + this.finalEvidenceDigest = Objects.requireNonNull(finalEvidenceDigest, "finalEvidenceDigest"); + if (!finalEvidenceDigest.matches("sha256:[0-9a-f]{64}") + || !finalEvidenceDigest.equals( + GameDesignDraftTerminalOperation.sha256(this.finalEvidenceBytes))) { + throw new IllegalArgumentException( + "Terminal evidence digest differs from exact evidence bytes"); + } + if (result == Result.COMMITTED + && !Arrays.equals( + this.finalEvidenceBytes, ownerResultVectorJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Committed terminal evidence must be the exact synchronized owner result vector"); + } + this.createdAt = Objects.requireNonNull(createdAt, "createdAt"); + } + + public GameDesignDraftTerminalOperation operation() { + return operation; + } + + public Result result() { + return result; + } + + public DraftAuthorizationFenceBinding.Owner owner() { + return DraftAuthorizationFenceBinding.Owner.GAME_DESIGN; + } + + /** + * Maps this durable Game Design result to Account's existing canonical owner-readback value. This + * is only a byte-for-byte schema adapter; it does not authenticate the producer or make this + * otherwise unregistered component an authorization source. + */ + public DraftAuthorizationFenceBinding.OwnerReadback toOwnerReadback() { + DraftAuthorizationFenceBinding accountBinding = operation.accountBinding(); + return new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.valueOf(result.name()), + accountBinding.operationId(), + accountBinding.commitId(), + accountBinding.fenceId(), + accountBinding.inputDigest(), + operation.accountBindingBytes(), + finalEvidenceBytes); + } + + public String ownerResultVectorJson() { + return ownerResultVectorJson; + } + + public byte[] finalEvidenceBytes() { + return finalEvidenceBytes.clone(); + } + + public String finalEvidenceDigest() { + return finalEvidenceDigest; + } + + public OffsetDateTime createdAt() { + return createdAt; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOutcome other) { + return other != null + && operation.exactlyMatches(other.operation) + && result == other.result + && ownerResultVectorJson.equals(other.ownerResultVectorJson) + && Arrays.equals(finalEvidenceBytes, other.finalEvidenceBytes) + && finalEvidenceDigest.equals(other.finalEvidenceDigest); + } + + private void validateOwnerResultVector() { + try { + byte[] vectorBytes = ownerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals( + vectorBytes, Rfc8785CanonicalJson.canonicalizeUtf8(ownerResultVectorJson))) { + throw new IllegalArgumentException("Terminal owner result vector is not canonical JSON"); + } + JsonNode vector = JSON.readTree(ownerResultVectorJson); + if (vector == null + || !vector.isArray() + || vector.size() != operation.gameDesignBinding().requiredOwners().size()) { + throw new IllegalArgumentException("Terminal owner result vector is incomplete"); + } + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + Owner expectedOwner = operation.gameDesignBinding().requiredOwners().get(index); + String expectedStatus = result == Result.COMMITTED ? "APPLIED" : null; + if (item == null + || !item.isObject() + || item.size() != 7 + || !text(item, "owner").equals(expectedOwner.name()) + || !text(item, "commitId").equals(operation.gameDesignBinding().commitId().toString()) + || !text(item, "bindingDigest").equals(operation.gameDesignBinding().digest()) + || (expectedStatus != null && !text(item, "status").equals(expectedStatus)) + || (result == Result.DEFINITIVELY_ABORTED + && !ListStatus.TERMINAL.contains(text(item, "status"))) + || !item.path("appliedEpochs").isArray() + || !item.path("resultBytesBase64").isTextual() + || !item.path("resultIdentity").isTextual()) { + throw new IllegalArgumentException( + "Terminal owner result vector differs from its complete commit binding"); + } + } + } catch (java.io.IOException exception) { + throw new IllegalArgumentException( + "Terminal owner result vector is not valid JSON", exception); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Terminal owner result is missing text field " + field); + } + return value.textValue(); + } + + private static final class ListStatus { + private static final java.util.Set TERMINAL = java.util.Set.of("APPLIED", "REJECTED"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java new file mode 100644 index 0000000000..ff51060387 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java @@ -0,0 +1,601 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local durable Account-operation claim and final Game Design outcome readback. + * + *

This class deliberately has no Spring component annotation or RPC registration. It stores + * exact source material and coordinator results only; it neither authenticates Account sources nor + * treats those results as Account's independent owner outcomes. + */ +public final class GameDesignDraftTerminalOutcomeRepository { + private static final String OPERATION_TABLE = "game_design_draft_terminal_operation"; + private static final String OUTCOME_TABLE = "game_design_draft_terminal_outcome"; + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + + private final DSLContext dsl; + + public GameDesignDraftTerminalOutcomeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Retains the exact original Account operation before any owner dispatch. The caller must hold + * the same canonical Version row lock used by coordinator transitions. + */ + GameDesignDraftTerminalOperation claim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + validateClaim(operation, lockedVersion); + DraftCommitBinding binding = operation.gameDesignBinding(); + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + return toOperation(byOperation); + } + if (dsl.fetchOne( + "SELECT 1 FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()) + == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitNotFoundException( + "Game Design commit must be claimed before its Account operation"); + } + + DraftAuthorizationFenceBinding account = operation.accountBinding(); + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, request_id, commit_id, fence_id, actor_account_id, " + + "canonical_tenant_id, canonical_version_id, base_commit_id, expected_draft_epoch, " + + "account_binding_bytes, account_binding_digest, game_design_binding_json, " + + "game_design_input_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.actorAccountId(), + account.tenantId(), + account.versionId(), + account.baseCommitId(), + account.expectedDraftEpoch(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + binding.canonicalJson(), + binding.digest()); + Record persistedRow = findOperation(account.operationId(), true); + if (persistedRow == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity conflicts with a retained Game Design binding"); + } + GameDesignDraftTerminalOperation persisted = toOperation(persistedRow); + requireExactOperation(operation, persisted); + return persisted; + } + + /** + * Fails before the coordinator creates any row if a supplied Account binding is not claimable. + */ + void validateClaim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(lockedVersion, "lockedVersion"); + DraftCommitBinding binding = operation.gameDesignBinding(); + if (!binding.target().equals(lockedVersion.target())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation differs from the same-Version claim lock"); + } + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return; + } + Record byCommit = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (byCommit != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "A Game Design commit is already claimed by a different Account operation"); + } + Record commit = + dsl.fetchOne( + "SELECT input_digest, binding_json, workflow_state FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit != null) { + DraftCommitBinding storedBinding = + DraftCommitBinding.fromStored( + commit.get("binding_json", String.class), commit.get("input_digest", String.class)); + requireExactGameDesignBinding(binding, storedBinding); + if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "Original Account operation must be retained before owner dispatch begins"); + } + } + if (!"DRAFT".equals(lockedVersion.versionState())) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation can be newly claimed only while its exact Version is DRAFT"); + } + Record slot = + dsl.fetchOne( + "SELECT 1 FROM game_design_draft_commit_application_slot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (slot != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation must be claimed before the Version dispatch slot is acquired"); + } + } + + /** Reads the immutable operation claim, whether or not a terminal outcome exists yet. */ + Optional readOperation(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + Record row = findOperation(operationId, false); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + /** + * Reads only an explicitly persisted terminal outcome. Empty means unresolved or unclaimed; it + * never means definitively aborted. + */ + Optional read(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + GameDesignDraftTerminalOperation operation = readOperation(operationId).orElse(null); + if (operation == null) { + return Optional.empty(); + } + Record row = findOutcome(operationId, false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(operation, row)); + } + + /** Exact-binding readback for Account; changed original bytes conflict instead of aliasing. */ + public Optional read(GameDesignDraftTerminalOperation expected) { + Objects.requireNonNull(expected, "expected"); + GameDesignDraftTerminalOperation persisted = + readOperation(expected.accountBinding().operationId()).orElse(null); + if (persisted == null) { + if (findOperation( + expected.gameDesignBinding().target(), + expected.gameDesignBinding().requestId(), + expected.gameDesignBinding().commitId(), + false) + != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design commit is retained under a different Account operation identity"); + } + return Optional.empty(); + } + requireExactOperation(expected, persisted); + Record row = findOutcome(expected.accountBinding().operationId(), false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(persisted, row)); + } + + /** + * Reconstructs only the complete binding already embedded in the original Account bytes, then + * reads its explicit immutable terminal row. Missing operation or result remains unresolved. + */ + public Optional readAccountBound( + byte[] originalAccountBindingBytes) { + requireCommittedReadBoundary(); + if (originalAccountBindingBytes == null || originalAccountBindingBytes.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + DraftAuthorizationFenceBinding accountBinding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBindingBytes.clone()); + return read(new GameDesignDraftTerminalOperation(accountBinding)); + } + + /** + * External Account readback cannot observe rows before the caller's owner transaction commits. + */ + private static void requireCommittedReadBoundary() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account-bound terminal readback requires a committed owner transaction boundary"); + } + } + + /** Records the local committed outcome in the same transaction as synchronized visibility. */ + Optional recordCommitted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.VisibilityFence visibilityFence, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + if (!visibilityFence.target().equals(binding.target()) + || !visibilityFence.requestId().equals(binding.requestId()) + || !visibilityFence.commitId().equals(binding.commitId()) + || !visibilityFence.inputDigest().equals(binding.digest()) + || !visibilityFence.resultVectorJson().equals(exactOwnerResultVectorJson)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Committed terminal evidence differs from the exact synchronized visibility fence"); + } + byte[] evidence = exactOwnerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + + /** Records the local no-commit outcome beside the exact abort tombstone and owner vector. */ + Optional recordAborted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.FinalAbortReceipt abortReceipt, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(abortReceipt, "abortReceipt"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + requireExactGameDesignBinding(binding, abortReceipt.binding()); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + + /** Prevents a late coordinator transition from mutating a definitively aborted operation. */ + void requireNotDefinitivelyAborted(DraftCommitBinding binding) { + Record operation = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operation == null) { + return; + } + Record outcome = findOutcome(operation.get("operation_id", UUID.class), true); + if (outcome != null + && GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED + .name() + .equals(outcome.get("outcome", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "A definitively aborted Account-bound Draft operation cannot accept a late writer"); + } + } + + boolean isAccountBound(DraftCommitBinding binding) { + return findOperation(binding.target(), binding.requestId(), binding.commitId(), false) != null; + } + + private GameDesignDraftTerminalOutcome insertOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + String evidenceDigest = GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes); + if (existing != null) { + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal outcome identity was reused with changed final evidence"); + } + return retained; + } + + dsl.execute( + "INSERT INTO " + + OUTCOME_TABLE + + " (operation_id, outcome, owner_result_vector_json, terminal_evidence_bytes, " + + "terminal_evidence_digest) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + operationId, + result.name(), + ownerResultVectorJson, + finalEvidenceBytes.clone(), + evidenceDigest); + Record persisted = findOutcome(operationId, true); + if (persisted == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result conflicts with another operation identity"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, persisted); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result retained different final evidence"); + } + return retained; + } + + private GameDesignDraftTerminalOutcome requireExistingOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result expectedResult, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + if (existing == null) { + throw new IllegalStateException( + "A retained Game Design terminal fence lacks its atomic Account-bound outcome row"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome expected = + new GameDesignDraftTerminalOutcome( + operation, + expectedResult, + ownerResultVectorJson, + finalEvidenceBytes, + GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes), + retained.createdAt()); + if (!retained.exactlyMatches(expected)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal readback differs from its retained final fence"); + } + return retained; + } + + private Record findOperation(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private Record findOperation( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + } + + private Record findOutcome(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OUTCOME_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private GameDesignDraftTerminalOperation toOperation(Record row) { + byte[] accountBytes = row.get("account_binding_bytes", byte[].class); + String accountDigest = row.get("account_binding_digest", String.class); + DraftAuthorizationFenceBinding account; + try { + account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Account Draft binding is corrupt", exception); + } + if (!GameDesignDraftTerminalOperation.sha256(accountBytes).equals(accountDigest) + || !account.operationId().equals(row.get("operation_id", UUID.class)) + || !account.requestId().equals(row.get("request_id", UUID.class)) + || !account.commitId().equals(row.get("commit_id", UUID.class)) + || !account.fenceId().equals(row.get("fence_id", UUID.class)) + || !account.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !account.tenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !account.versionId().equals(row.get("canonical_version_id", UUID.class)) + || !account.baseCommitId().equals(row.get("base_commit_id", String.class)) + || !account.expectedDraftEpoch().equals(row.get("expected_draft_epoch", String.class))) { + throw new IllegalStateException( + "Stored Account Draft binding differs from its indexed identity"); + } + DraftCommitBinding gameDesignBinding = + DraftCommitBinding.fromStored( + row.get("game_design_binding_json", String.class), + row.get("game_design_input_digest", String.class)); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, gameDesignBinding); + if (!Arrays.equals(accountBytes, operation.accountBindingBytes())) { + throw new IllegalStateException("Persisted Account Draft binding is not canonical"); + } + return operation; + } + + private GameDesignDraftTerminalOutcome toOutcome( + GameDesignDraftTerminalOperation operation, Record row) { + byte[] evidence = row.get("terminal_evidence_bytes", byte[].class); + String evidenceDigest = row.get("terminal_evidence_digest", String.class); + if (!GameDesignDraftTerminalOperation.sha256(evidence).equals(evidenceDigest)) { + throw new IllegalStateException("Persisted terminal evidence digest differs from its bytes"); + } + return new GameDesignDraftTerminalOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.valueOf(row.get("outcome", String.class)), + row.get("owner_result_vector_json", String.class), + evidence, + evidenceDigest, + row.get("created_at", OffsetDateTime.class)); + } + + /** + * Confirms that a returned status row still has its exact durable coordinator terminal fence; + * workflow status alone is never treated as a participant result. + */ + private GameDesignDraftTerminalOutcome readAndVerifyTerminalOutcome( + GameDesignDraftTerminalOperation operation, Record outcomeRow) { + GameDesignDraftTerminalOutcome outcome = toOutcome(operation, outcomeRow); + DraftCommitBinding binding = operation.gameDesignBinding(); + Record commit = + dsl.fetchOne( + "SELECT workflow_state, input_digest, binding_json FROM " + + COMMIT_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 (commit == null + || !binding.digest().equals(commit.get("input_digest", String.class)) + || !binding.canonicalJson().equals(commit.get("binding_json", String.class))) { + throw new IllegalStateException( + "Game Design terminal outcome lacks its exact retained coordinator commit"); + } + + if (outcome.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json FROM " + + VISIBILITY_FENCE_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 (!"SYNCHRONIZED".equals(commit.get("workflow_state", String.class)) + || fence == null + || !binding.digest().equals(fence.get("input_digest", String.class)) + || !outcome.ownerResultVectorJson().equals(fence.get("result_vector_json", String.class)) + || !Arrays.equals( + outcome.finalEvidenceBytes(), + outcome.ownerResultVectorJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException( + "Committed Game Design terminal outcome lacks its exact synchronized visibility fence"); + } + return outcome; + } + + Record abort = + dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes FROM " + + FINAL_ABORT_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()); + Record fence = + dsl.fetchOne( + "SELECT 1 FROM " + + VISIBILITY_FENCE_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 (!"FAILED_NONPUBLICATION".equals(commit.get("workflow_state", String.class)) + || abort == null + || !binding.digest().equals(abort.get("input_digest", String.class)) + || !binding.canonicalJson().equals(abort.get("binding_json", String.class)) + || !Arrays.equals(outcome.finalEvidenceBytes(), abort.get("abort_bytes", byte[].class)) + || fence != null) { + throw new IllegalStateException( + "Aborted Game Design terminal outcome lacks its exact final-abort tombstone"); + } + return outcome; + } + + private void requireExactOperation( + GameDesignDraftTerminalOperation expected, GameDesignDraftTerminalOperation actual) { + if (!expected.exactlyMatches(actual)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity was reused with changed original canonical bytes"); + } + } + + private void requireExactGameDesignBinding( + DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Terminal operation differs from its complete canonical Game Design binding"); + } + } + + 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( + "Game Design terminal mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java new file mode 100644 index 0000000000..e1d831cce1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; + +/** Exact versioned owner evidence frozen when a proposal is reviewed; grants no authorization. */ +public final class GameDesignReviewedBaseEvidence { + public static final String SCHEMA = "game-design-reviewed-draft-base/v1"; + private final TargetProof target; + private final DraftBaseReference reference; + private final byte[] bytes; + private final String digest; + + private GameDesignReviewedBaseEvidence( + TargetProof target, DraftBaseReference reference, byte[] ownerEvidence) { + this.target = Objects.requireNonNull(target, "target"); + this.reference = Objects.requireNonNull(reference, "reference"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, SCHEMA); + frame(out, DraftBaseReference.SCHEMA); + frame(out, reference.kind().name()); + frame(out, reference.canonicalValue()); + frame(out, target.canonicalTenantId().toString()); + frame(out, target.canonicalVersionId().toString()); + frame(out, Long.toString(target.gameDesignVersionRowId())); + frame(out, target.gameDesignVersionTenantKey()); + frame(out, Long.toString(target.sourceGameRowId())); + frame(out, target.sourceGameTenantKey()); + frame(out, target.sourceProvenanceKind()); + DraftAuthorizationFenceBinding.frame(out, ownerEvidence); + bytes = out.toByteArray(); + digest = DraftAuthorizationFenceBinding.digest(bytes); + } + + public static GameDesignReviewedBaseEvidence genesis(GameDesignSourceRepository.Genesis genesis) { + Objects.requireNonNull(genesis, "genesis"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, "shared-policy-command-genesis/v1"); + frame(out, genesis.policy().creationTransactionId()); + DraftAuthorizationFenceBinding.frame(out, genesis.policy().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, genesis.command().canonicalBytes()); + return new GameDesignReviewedBaseEvidence( + genesis.policy().target(), + new DraftBaseReference(DraftBaseReference.Kind.GENESIS, genesis.policy().receiptId()), + out.toByteArray()); + } + + public static GameDesignReviewedBaseEvidence authored( + GameDesignSourceRepository.SynchronizedSources sources, + DraftCommitCoordinatorRepository.CommitSnapshot retained) { + Objects.requireNonNull(sources, "sources"); + Objects.requireNonNull(retained, "retained"); + DraftCommitBinding binding = sources.command().binding(); + if (!binding.equals(retained.binding()) + || retained.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED + || !retained.ownerStates().keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new IllegalArgumentException( + "Exact retained synchronized base and owner vector required"); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, "retained-authored-policy-command-base/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, sources.policy().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, sources.command().canonicalBytes()); + frame(out, Integer.toString(binding.requiredOwners().size())); + for (var owner : binding.requiredOwners()) { + var state = retained.ownerStates().get(owner); + var outcome = state.outcome().orElseThrow(); + if (state.status() != DraftCommitCoordinatorRepository.OwnerStatus.APPLIED + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest()) + || outcome.appliedEpochs().size() != binding.affectedUnits(owner).size() + || binding.affectedUnits(owner).stream() + .anyMatch( + unit -> + outcome.appliedEpochs().stream() + .noneMatch( + epoch -> + epoch.aggregateType().equals(unit.aggregateType()) + && epoch.aggregateId().equals(unit.aggregateId()) + && epoch.scopeType().equals(unit.scopeType()) + && epoch.scopeId().equals(unit.scopeId()) + && epoch.expectedEpoch().equals(unit.expectedEpoch())))) { + throw new IllegalArgumentException("Complete exact APPLIED base owner evidence required"); + } + frame(out, owner.name()); + frame(out, outcome.status().name()); + frame(out, outcome.commitId().toString()); + frame(out, outcome.bindingDigest()); + frame(out, outcome.resultIdentity()); + DraftAuthorizationFenceBinding.frame(out, outcome.resultBytes()); + frame(out, Integer.toString(outcome.appliedEpochs().size())); + for (var epoch : outcome.appliedEpochs()) { + frame(out, epoch.aggregateType()); + frame(out, epoch.aggregateId()); + frame(out, epoch.scopeType()); + frame(out, epoch.scopeId()); + frame(out, epoch.expectedEpoch()); + frame(out, epoch.resultingEpoch()); + } + } + return new GameDesignReviewedBaseEvidence( + binding.target(), + new DraftBaseReference(DraftBaseReference.Kind.AUTHORED_COMMIT, binding.commitId()), + out.toByteArray()); + } + + public TargetProof target() { + return target; + } + + public DraftBaseReference reference() { + return reference; + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public String digest() { + return digest; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + @Override + public boolean equals(Object other) { + return other instanceof GameDesignReviewedBaseEvidence evidence + && Arrays.equals(bytes, evidence.bytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(bytes); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java new file mode 100644 index 0000000000..56439d2c92 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal prerequisite for the canonical reviewed-source ingress; no authentication is implied. + */ +public final class GameDesignReviewedBaseRepository { + private final DSLContext dsl; + private final GameDesignSourceRepository sources; + private final DraftCommitCoordinatorRepository coordinator; + + public GameDesignReviewedBaseRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + sources = new GameDesignSourceRepository(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + /** Resolve exact owner provenance when preparing the immutable review, under the Version lock. */ + public GameDesignReviewedBaseEvidence resolve(TargetProof target, DraftBaseReference reference) { + requireWrite(); + lockDraft(target); + Objects.requireNonNull(reference, "reference"); + if (reference.kind() == DraftBaseReference.Kind.GENESIS) { + var genesis = + sources + .readGenesis(target) + .orElseThrow(() -> new IllegalStateException("REVIEWED_BASE_GENESIS_UNAVAILABLE")); + if (!reference.identity().equals(genesis.policy().receiptId())) { + throw new IllegalArgumentException("REVIEWED_BASE_GENESIS_IDENTITY_CONFLICT"); + } + return GameDesignReviewedBaseEvidence.genesis(genesis); + } + var synchronizedSources = + sources + .readSynchronized(target, reference.identity()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_SOURCE_UNAVAILABLE")); + var binding = synchronizedSources.command().binding(); + var retained = + coordinator + .read(target, binding.requestId()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_COMMIT_UNAVAILABLE")); + if (!reference.identity().equals(binding.commitId())) { + throw new IllegalArgumentException("REVIEWED_BASE_AUTHORED_IDENTITY_CONFLICT"); + } + return GameDesignReviewedBaseEvidence.authored(synchronizedSources, retained); + } + + /** + * Compare the frozen reviewed bytes to actual owner evidence before claiming a new coordinator + * binding. Exact retries compare retained bytes and never re-resolve or replace their provenance. + * Account authorization and semantic affected-set verification remain caller obligations. + */ + public DraftCommitCoordinatorRepository.CommitSnapshot claimReviewed( + DraftCommitBinding binding, GameDesignReviewedBaseEvidence expectedReviewedEvidence) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(expectedReviewedEvidence, "expectedReviewedEvidence"); + var reference = DraftBaseReference.parse(binding.baseCommitId()); + if (!binding.target().equals(expectedReviewedEvidence.target()) + || !reference.equals(expectedReviewedEvidence.reference())) { + throw new IllegalArgumentException("REVIEWED_BASE_BINDING_CONFLICT"); + } + var locked = + coordinator.lockVersionTarget( + binding.target().canonicalTenantId(), binding.target().canonicalVersionId()); + if (!binding.target().equals(locked.target())) { + throw new IllegalArgumentException("REVIEWED_BASE_TARGET_CONFLICT"); + } + Optional existing = read(binding); + if (existing.isPresent()) { + requireExact(expectedReviewedEvidence, existing.orElseThrow()); + return coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + } + // A previously opaque claim cannot be retroactively decorated with invented reviewed evidence. + if (coordinator.read(binding.target(), binding.requestId()).isPresent()) { + throw new IllegalStateException("REVIEWED_BASE_EXISTING_CLAIM_LACKS_EVIDENCE"); + } + var resolved = resolve(binding.target(), reference); + if (!resolved.equals(expectedReviewedEvidence)) { + throw new IllegalArgumentException("REVIEWED_BASE_OWNER_EVIDENCE_CONFLICT"); + } + var result = coordinator.claim(binding); + dsl.execute( + "INSERT INTO game_design_reviewed_draft_base " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest, " + + "binding_json, base_kind, base_identity, base_reference, evidence_schema, " + + "evidence_bytes, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + reference.kind().name(), + reference.identity(), + reference.canonicalValue(), + GameDesignReviewedBaseEvidence.SCHEMA, + resolved.canonicalBytes(), + resolved.digest()); + requireExact(resolved, read(binding).orElseThrow()); + return result; + } + + /** Immutable exact-binding readback, including the original bytes and their versioned digest. */ + public Optional read(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_reviewed_draft_base WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND (request_id = ? OR commit_id = ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var reference = DraftBaseReference.parse(binding.baseCommitId()); + if (!binding.equals( + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class))) + || !reference.kind().name().equals(row.get("base_kind", String.class)) + || !reference.identity().equals(row.get("base_identity", java.util.UUID.class)) + || !reference.canonicalValue().equals(row.get("base_reference", String.class)) + || !GameDesignReviewedBaseEvidence.SCHEMA.equals( + row.get("evidence_schema", String.class))) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + } + var result = + new ReviewedBaseReadback( + row.get("evidence_bytes", byte[].class), row.get("evidence_digest", String.class)); + return Optional.of(result); + } + + /** Require original immutable review provenance for source writes and publication consumption. */ + public ReviewedBaseReadback requireRetained(DraftCommitBinding binding) { + var retained = + read(binding) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE")); + var commit = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_COMMIT_UNAVAILABLE")); + if (!binding.equals(commit.binding())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + } + return retained; + } + + private void lockDraft(TargetProof target) { + Objects.requireNonNull(target, "target"); + var version = + coordinator.lockVersionTarget(target.canonicalTenantId(), target.canonicalVersionId()); + if (!target.equals(version.target()) + || !"DRAFT".equals(version.versionState()) + || version.scriptOnly() + || version.baseVersionId() != null + || version.scriptPatchVersion() != null) { + throw new IllegalArgumentException("REVIEWED_BASE_EXACT_FULL_DRAFT_REQUIRED"); + } + } + + private static void requireExact( + GameDesignReviewedBaseEvidence expected, ReviewedBaseReadback stored) { + if (!expected.digest().equals(stored.digest()) + || !Arrays.equals(expected.canonicalBytes(), stored.canonicalBytes())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_EVIDENCE_CONFLICT"); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Reviewed base requires caller-owned writable READ_COMMITTED transaction"); + } + } + + public record ReviewedBaseReadback(byte[] canonicalBytes, String digest) { + public ReviewedBaseReadback { + canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(digest)) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_DIGEST_CONFLICT"); + } + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java index ab51eeb0da..b9ef9861f4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java @@ -12,6 +12,7 @@ public class PublishAttempt { private String publishWorkflowId; private PublishType publishType; private PublishAttemptStatus status = PublishAttemptStatus.PENDING; + private long revision = 1L; private Long versionId; private int versionNumber; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java index 7062b7542a..e4fbe31ab3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java @@ -10,5 +10,6 @@ public enum PublishGateFailureCode { APPLIED_COMMIT_MISMATCH, RECORDED_SCOPE_MISMATCH, RECORDED_DIGEST_SCHEMA_MISMATCH, - RECORDED_CONTENT_DIGEST_MISMATCH + RECORDED_CONTENT_DIGEST_MISMATCH, + INVALID_REALM_ENTRY_POLICY_SET } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java new file mode 100644 index 0000000000..65f7993ee8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact staged command-source application evidence, separate from the combined owner outcome. */ +public record CommandApplication( + DraftCommitBinding binding, + UUID inheritedCommitId, + String expectedEpoch, + List mutations, + CommandSnapshot snapshot) { + public CommandApplication { + Objects.requireNonNull(binding, "binding"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + requireCounter(expectedEpoch); + mutations = List.copyOf(Objects.requireNonNull(mutations, "mutations")); + if (mutations.isEmpty()) { + throw new IllegalArgumentException( + "Command application must contain explicit command mutations"); + } + if (!CommandSource.mutationsFromStored(CommandSource.mutationsJson(mutations)) + .equals(mutations)) { + throw new IllegalArgumentException( + "Command application mutations must retain canonical revision order"); + } + Objects.requireNonNull(snapshot, "snapshot"); + if (!binding.equals(snapshot.binding()) + || !Objects.equals(inheritedCommitId, snapshot.inheritedCommitId()) + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch()) + || mutations.stream() + .anyMatch(mutation -> !binding.commitId().equals(mutation.commitId()))) { + throw new IllegalArgumentException( + "Command application evidence differs from its exact binding"); + } + List commandScopes = + binding.affectedUnits(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(CommandApplication::isCommandScope) + .toList(); + if (commandScopes.size() != 1 + || !expectedEpoch.equals(commandScopes.getFirst().expectedEpoch())) { + throw new IllegalArgumentException("Exact command source scope and epoch are required"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, CommandSource.APPLICATION_SCHEMA); + DraftAuthorizationFenceBinding.frame( + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, CommandSource.mutationsJson(mutations)); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String resultIdentity() { + return "command-source:" + binding.commitId() + ":" + CommandSource.sha256(canonicalBytes()); + } + + public AppliedEpoch commandAppliedEpoch() { + return new AppliedEpoch( + CommandSource.SCOPE, + binding.target().canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + private static boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void requireCounter(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("expectedEpoch must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java new file mode 100644 index 0000000000..a4085e12d4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective command set captured at one actual synchronized Draft commit. */ +public record CommandSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + String genesisReceiptDigest, + List definitions) { + public CommandSnapshot { + Objects.requireNonNull(binding, "binding"); + requireCounter(sourceEpoch, "sourceEpoch"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + if (genesisReceiptDigest == null || !genesisReceiptDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact command source genesis receipt digest required"); + } + definitions = List.copyOf(Objects.requireNonNull(definitions, "definitions")); + CommandSource.requireCanonicalDefinitions(definitions); + } + + @Override + public List definitions() { + return List.copyOf(definitions); + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + CommandSource.SNAPSHOT_SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptDigest", + genesisReceiptDigest, + "definitions", + CommandSource.tree(CommandSource.definitionsJson(definitions)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static CommandSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptDigest", + "definitions"); + if (!CommandSource.SNAPSHOT_SCHEMA.equals(CommandSource.requiredStoredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported command source snapshot schema"); + } + var inheritedNode = root.get("inheritedCommitId"); + if (inheritedNode == null || !inheritedNode.isTextual()) { + throw new IllegalArgumentException("Stored command source inheritedCommitId must be text"); + } + String inherited = inheritedNode.textValue(); + UUID inheritedCommitId = inherited.isEmpty() ? null : UUID.fromString(inherited); + if (inheritedCommitId != null && !inheritedCommitId.toString().equals(inherited)) { + throw new IllegalArgumentException( + "Stored command source inheritedCommitId must be a canonical UUID"); + } + var result = + new CommandSnapshot( + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")), + CommandSource.requiredStoredText(root, "sourceEpoch"), + inheritedCommitId, + CommandSource.requiredStoredText(root, "genesisReceiptDigest"), + CommandSource.definitionsFromStored(root.get("definitions").toString())); + if (!result.canonicalJson().equals(json)) { + throw new IllegalArgumentException( + "Stored command source snapshot is not exact canonical JSON"); + } + return result; + } + + /** Frozen source paired with the actual operation bytes and selected synchronized snapshot. */ + public record Capture(GameDesignPublicationOperation operation, CommandSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(snapshot, "snapshot"); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen command source differs from the exact selected synchronized commit"); + } + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-command-source-capture/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, operation.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java new file mode 100644 index 0000000000..e833008d33 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -0,0 +1,647 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +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.Owner; +import net.firedevops.firemud.common.command.CommandEffectDeclarationConstraints; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Typed complete effective source for Game Design's authored command definitions. */ +public final class CommandSource { + public static final String SCOPE = "COMMAND_DEFINITION_SET"; + public static final String SCOPE_ID = "effective"; + public static final String SNAPSHOT_SCHEMA = "game-design-command-source-snapshot/v1"; + public static final String APPLICATION_SCHEMA = "game-design-command-source-application/v1"; + public static final String REALM_POLICY_REVISION_KIND = "REALM_ENTRY_POLICY"; + + private static final String REVISION_KIND = "COMMAND_DEFINITION"; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0, 0); + private static final ObjectMapper JSON = new ObjectMapper(); + + private CommandSource() {} + + public enum OperationKind { + UPSERT, + DELETE + } + + /** One exact authored command definition with its creating revision and commit provenance. */ + public record Definition( + String commandId, + String definitionJson, + UUID sourceCommitId, + UUID sourceRevisionId, + String revisionOrder) { + public Definition { + requireText(commandId, "commandId"); + Objects.requireNonNull(definitionJson, "definitionJson"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + requireCounter(revisionOrder, "revisionOrder"); + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Command source key differs from the exact definition"); + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + } + + /** One explicit command mutation. DELETE retains identity and source revision provenance. */ + public record Mutation( + String revisionOrder, + UUID revisionId, + UUID commitId, + OperationKind operation, + String commandId, + String definitionJson) { + public Mutation { + requireCounter(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(operation, "operation"); + requireText(commandId, "commandId"); + if ((operation == OperationKind.UPSERT) != (definitionJson != null)) { + throw new IllegalArgumentException("Command mutation definition presence is invalid"); + } + if (definitionJson != null) { + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Upsert identity differs from its command definition"); + } + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + + public Map canonicalObject() { + Map value = new LinkedHashMap<>(); + value.put("revisionOrder", revisionOrder); + value.put("revisionId", revisionId.toString()); + value.put("commitId", commitId.toString()); + value.put("operation", operation.name()); + value.put("commandId", commandId); + if (definitionJson != null) value.put("definitionJson", definitionJson); + return value; + } + } + + /** Exact receipt supplied only by the owner path that inserted a genuinely new Draft Version. */ + public record NewDraftGenesisReceipt( + DraftCommitBinding.TargetProof target, UUID receiptId, String creationTransactionId) { + public NewDraftGenesisReceipt { + Objects.requireNonNull(target, "target"); + requireNonNil(receiptId, "receiptId"); + if (creationTransactionId == null || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Exact Version insertion transaction identity is required"); + } + } + + public String targetProofJson() { + return canonical(targetObject(target)); + } + + public byte[] canonicalBytes() { + return canonical( + Map.of( + "schema", + "game-design-command-source-new-draft-genesis/v1", + "targetProof", + tree(targetProofJson()), + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId)) + .getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return sha256(canonicalBytes()); + } + } + + /** + * Converts the closed Draft owner payloads to command mutations. Realm policy payloads are a + * separate Game Design owner scope and are deliberately left for their own source writer. Unknown + * kinds deny rather than being guessed from omitted or legacy rows. + */ + public static List mutations(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + List mutations = new ArrayList<>(); + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) continue; + if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + if (!payload.path("schemaVersion").isInt() + || payload.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command source operation schema"); + } + String operation = requiredText(payload, "operation"); + if ("UPSERT".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "definitionJson"); + String definitionJson = requiredText(payload, "definitionJson"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.UPSERT, + commandIdFrom(definitionJson), + definitionJson)); + } else if ("DELETE".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "commandId"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.DELETE, + requiredText(payload, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Unsupported command source operation"); + } + } + return List.copyOf(mutations); + } + + public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + boolean found = false; + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { + found = true; + } else if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + } + return found; + } + + /** Payload builder for a new immutable Draft binding; its result is part of binding.digest(). */ + public static String upsertPayload(String definitionJson) { + validateCommandDefinition(definitionJson); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "UPSERT", + "definitionJson", definitionJson)); + } + + /** + * Payload builder for an explicit digest-bound delete; absence is never interpreted as delete. + */ + public static String deletePayload(String commandId) { + requireText(commandId, "commandId"); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "DELETE", + "commandId", commandId)); + } + + public static List replay(List inherited, List mutations) { + Objects.requireNonNull(inherited, "inherited"); + Objects.requireNonNull(mutations, "mutations"); + Map effective = new HashMap<>(); + for (Definition definition : inherited) { + if (effective.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Inherited command source repeats a stable command key"); + } + } + String previousOrder = null; + UUID commitId = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : mutations) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || (commitId != null && !commitId.equals(mutation.commitId())) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Command mutations must retain one canonical commit and increasing revision order"); + } + previousOrder = mutation.revisionOrder(); + commitId = mutation.commitId(); + if (mutation.operation() == OperationKind.DELETE) { + if (effective.remove(mutation.stableKey()) == null) { + throw new IllegalArgumentException("Cannot delete an absent command definition key"); + } + } else { + effective.put( + mutation.stableKey(), + new Definition( + mutation.commandId(), + mutation.definitionJson(), + mutation.commitId(), + mutation.revisionId(), + mutation.revisionOrder())); + } + } + List result = + effective.values().stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + validateDistinctCommandTokens(result); + return result; + } + + static String definitionsJson(List definitions) { + return canonical( + definitions.stream() + .sorted(Comparator.comparing(Definition::stableKey)) + .map(CommandSource::definitionObject) + .toList()); + } + + static List definitionsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) throw new IllegalArgumentException("Complete command array is required"); + List definitions = new ArrayList<>(); + for (JsonNode item : root) { + fields( + item, + "commandId", + "definitionJson", + "sourceCommitId", + "sourceRevisionId", + "revisionOrder"); + definitions.add( + new Definition( + requiredText(item, "commandId"), + requiredText(item, "definitionJson"), + UUID.fromString(requiredText(item, "sourceCommitId")), + UUID.fromString(requiredText(item, "sourceRevisionId")), + requiredText(item, "revisionOrder"))); + } + List result = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitionsJson(result).equals(json)) { + throw new IllegalArgumentException("Stored command source set is not canonical"); + } + validateDistinctCommandTokens(result); + return List.copyOf(result); + } + + static String mutationsJson(List mutations) { + return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); + } + + static List mutationsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) + throw new IllegalArgumentException("Complete command operation list is required"); + List result = new ArrayList<>(); + for (JsonNode item : root) { + String operation = requiredText(item, "operation"); + if ("UPSERT".equals(operation)) { + fields( + item, + "revisionOrder", + "revisionId", + "commitId", + "operation", + "commandId", + "definitionJson"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.UPSERT, + requiredText(item, "commandId"), + requiredText(item, "definitionJson"))); + } else if ("DELETE".equals(operation)) { + fields(item, "revisionOrder", "revisionId", "commitId", "operation", "commandId"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.DELETE, + requiredText(item, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Stored command operation kind is unsupported"); + } + } + String previousOrder = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : result) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Stored command operations are not in exact revision order"); + } + previousOrder = mutation.revisionOrder(); + } + return List.copyOf(result); + } + + static void requireCanonicalDefinitions(List definitions) { + List sorted = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitions.equals(sorted)) { + throw new IllegalArgumentException( + "Command source definitions are not in canonical stable-key order"); + } + Map unique = new HashMap<>(); + for (Definition definition : definitions) { + if (unique.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Command source repeats a stable command key"); + } + } + validateDistinctCommandTokens(definitions); + } + + static void requireStoredFields(JsonNode node, String... fields) { + CommandSource.fields(node, fields); + } + + static String requiredStoredText(JsonNode node, String field) { + return requiredText(node, field); + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical command source encoding failed", failure); + } + } + + static JsonNode tree(String json) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(json)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous command source JSON required", failure); + } + } + + static byte[] canonicalBytes(String json) { + return json.getBytes(StandardCharsets.UTF_8); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } + + static Map targetObject(DraftCommitBinding.TargetProof target) { + Map result = new LinkedHashMap<>(); + result.put("canonicalTenantId", target.canonicalTenantId().toString()); + result.put("canonicalVersionId", target.canonicalVersionId().toString()); + result.put("gameDesignVersionRowId", target.gameDesignVersionRowId()); + result.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + result.put("sourceGameRowId", target.sourceGameRowId()); + result.put("sourceGameTenantKey", target.sourceGameTenantKey()); + result.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return result; + } + + private static Map definitionObject(Definition definition) { + return Map.of( + "commandId", definition.commandId(), + "definitionJson", definition.definitionJson(), + "sourceCommitId", definition.sourceCommitId().toString(), + "sourceRevisionId", definition.sourceRevisionId().toString(), + "revisionOrder", definition.revisionOrder()); + } + + private static void validateDistinctCommandTokens(List definitions) { + Map tokenOwners = new HashMap<>(); + Map commandIds = new HashMap<>(); + for (Definition definition : definitions) { + String commandId = normalizeToken(definition.commandId()); + if (commandIds.putIfAbsent(commandId, Boolean.TRUE) != null) { + throw new IllegalArgumentException("Duplicate command definition id " + commandId); + } + ensureSingleTokenOwner(tokenOwners, commandId, commandId); + JsonNode aliases = tree(definition.definitionJson()).get("aliases"); + for (JsonNode alias : aliases) { + String normalized = normalizeToken(alias.asText()); + ensureSingleTokenOwner(tokenOwners, normalized, commandId); + } + } + } + + private static void ensureSingleTokenOwner( + Map owners, String token, String commandId) { + String existing = owners.putIfAbsent(token, commandId); + if (existing != null && !existing.equals(commandId)) { + throw new IllegalArgumentException("Ambiguous published command token " + token); + } + } + + private static String commandIdFrom(String definitionJson) { + validateCommandDefinition(definitionJson); + return requiredText(tree(definitionJson), "commandId"); + } + + /** Mirrors the currently accepted revision and release schema while preserving the raw JSON. */ + private static void validateCommandDefinition(String json) { + JsonNode definition = tree(json); + if (!definition.isObject() || definition.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command definition schema"); + } + requiredText(definition, "commandId"); + requiredText(definition, "semanticOwner"); + requireEnum(definition, "executionDiscipline", "DURABLE_GAMEPLAY"); + requireEnum(definition, "stageRequirement", "NONE", "LOGIN", "GAMEPLAY"); + requireEnum(definition, "promptPolicy", "NEVER", "WHEN_LOGGED_IN", "WHEN_GAMEPLAY"); + requireEnum(definition, "actionCategory", "GAMEPLAY", "SOCIAL", "META", "ADMIN", "SYSTEM"); + JsonNode history = definition.get("historyRecordable"); + if (history == null || !history.isBoolean()) { + throw new IllegalArgumentException("historyRecordable must be a boolean"); + } + requireTextArray(definition, "aliases"); + requireEnumArray( + definition, + "actionTags", + "MOVEMENT", + "COMMUNICATION", + "COMBAT", + "INVENTORY", + "WORLD_BROWSE", + "SOCIAL_PRESENCE", + "AUTHORING", + "SESSION", + "UI"); + JsonNode effects = definition.get("effects"); + if (effects == null || !effects.isArray()) { + throw new IllegalArgumentException("effects must be an array"); + } + for (JsonNode effect : effects) validateEffect(effect); + } + + private static void validateEffect(JsonNode effect) { + if (!effect.isObject() + || !"APPLY_ACTION_STATE".equals(requiredText(effect, "effectKind")) + || !effect.path("schemaVersion").isInt() + || effect.path("schemaVersion").asInt() != 1 + || !"SELF".equals(requiredText(effect, "targeting")) + || !"EFFECT_IDEMPOTENT".equals(requiredText(effect, "replayPolicy"))) { + throw new IllegalArgumentException("Unsupported command effect declaration"); + } + JsonNode payload = effect.get("payload"); + if (payload == null || !payload.isObject()) + throw new IllegalArgumentException("Effect payload must be an object"); + requireIdentifier(payload, "conditionKey"); + JsonNode duration = payload.get("durationSeconds"); + if (duration == null + || !duration.isInt() + || !CommandEffectDeclarationConstraints.isValidDurationSeconds(duration.asInt())) { + throw new IllegalArgumentException("Command action-state duration is unsupported"); + } + JsonNode effectPayload = payload.get("effectPayload"); + JsonNode modifiers = effectPayload == null ? null : effectPayload.get("modifiers"); + if (effectPayload == null + || !effectPayload.isObject() + || modifiers == null + || !modifiers.isArray()) { + throw new IllegalArgumentException("Command effect modifiers must be an array"); + } + for (JsonNode modifier : modifiers) { + if (!modifier.isObject()) + throw new IllegalArgumentException("Command effect modifier must be an object"); + String operation = requiredText(modifier, "operation"); + if (!CommandEffectDeclarationConstraints.SUPPORTED_MODIFIER_OPERATIONS.contains(operation)) { + throw new IllegalArgumentException("Unsupported command effect modifier operation"); + } + requireIdentifier(modifier, "target_key"); + JsonNode value = modifier.get("value"); + if (value == null || !value.isNumber()) + throw new IllegalArgumentException("Command effect modifier value must be numeric"); + optionalIdentifier(modifier, "scope_kind"); + optionalIdentifier(modifier, "scope_key"); + JsonNode priority = modifier.get("priority"); + if (priority != null && !priority.isInt()) + throw new IllegalArgumentException("Command effect priority must be an integer"); + } + } + + private static void requireIdentifier(JsonNode source, String field) { + String value = requiredText(source, field); + if (!CommandEffectDeclarationConstraints.isIdentifier(value)) { + throw new IllegalArgumentException("Command effect identifier is invalid: " + field); + } + } + + private static void optionalIdentifier(JsonNode source, String field) { + if (source.get(field) != null) requireIdentifier(source, field); + } + + private static void requireEnum(JsonNode source, String field, String... allowed) { + String actual = requiredText(source, field); + for (String value : allowed) if (value.equals(actual)) return; + throw new IllegalArgumentException("Unsupported command definition field " + field); + } + + private static void requireEnumArray(JsonNode source, String field, String... allowed) { + requireTextArray(source, field); + List supported = List.of(allowed); + for (JsonNode item : source.get(field)) { + if (!supported.contains(item.asText())) { + throw new IllegalArgumentException("Unsupported command definition value in " + field); + } + } + } + + private static void requireTextArray(JsonNode source, String field) { + JsonNode values = source.get(field); + if (values == null || !values.isArray()) { + throw new IllegalArgumentException("Command definition array is required: " + field); + } + for (JsonNode value : values) { + if (!value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException( + "Command definition array has an invalid entry: " + field); + } + } + } + + private static String requiredText(JsonNode source, String field) { + JsonNode value = source.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException("Command definition text is required: " + field); + } + return value.asText(); + } + + private static String normalizeToken(String token) { + if (token == null || token.isBlank()) { + throw new IllegalArgumentException("Command token must not be blank"); + } + return token.trim().toLowerCase(Locale.ROOT); + } + + private static void fields(JsonNode node, String... names) { + if (!node.isObject() || node.size() != names.length) { + throw new IllegalArgumentException("Closed command source operation fields are required"); + } + for (String name : names) { + if (node.get(name) == null) + throw new IllegalArgumentException("Missing command source field " + name); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank() || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException(name + " must be nonblank valid UTF-8 text"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) + throw new IllegalArgumentException(name + " must be non-nil"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java new file mode 100644 index 0000000000..ffc60d15a4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -0,0 +1,809 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage for a complete effective command set. Writes require the caller's + * coordinator transaction; this repository does not register an owner outcome or authorize a + * publication. + */ +public final class CommandSourceRepository { + private final DSLContext dsl; + + public CommandSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Explicit empty genesis for a Version known by its creation owner to be newly inserted as a + * Draft. Call only in that exact Version insertion transaction. Missing source rows alone never + * establish genesis, and this receipt is not a Draft commit. + */ + public CommandSource.NewDraftGenesisReceipt enrollNewDraftGenesis( + CommandSource.NewDraftGenesisReceipt receipt) { + requireWrite(); + Objects.requireNonNull(receipt, "receipt"); + TargetProof target = receipt.target(); + lockAuthority(target); + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || !Long.valueOf(1L).equals(version.get("version_state_epoch", Long.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_REQUIRES_NEW_FULL_DRAFT_EPOCH_ONE"); + } + Optional existing = baseline(target); + if (existing.isPresent()) { + Record row = existing.orElseThrow(); + if (!Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class)) + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !receipt.receiptId().equals(row.get("receipt_id", UUID.class)) + || !receipt + .creationTransactionId() + .equals(row.get("creation_transaction_id", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), true); + if (head(target).isPresent() + || new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).isPresent()) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_AFTER_DRAFT_COMMIT_DENIED"); + } + dsl.execute( + "INSERT INTO game_design_command_source_baseline " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, baseline_kind, " + + "receipt_id, creation_transaction_id, target_proof_json, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, 'NEW_DRAFT_EMPTY', ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + receipt.receiptId(), + receipt.creationTransactionId(), + receipt.targetProofJson(), + receipt.canonicalBytes(), + receipt.digest()); + dsl.execute( + "INSERT INTO game_design_command_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, applied_commit_id, baseline_digest) " + + "VALUES (?, ?, '0', NULL, NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.digest()); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + + /** Exact readback of an explicitly enrolled empty new-Draft baseline; absence stays absent. */ + public Optional readNewDraftGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + Optional stored = baseline(target); + if (stored.isEmpty()) return Optional.empty(); + Record row = stored.orElseThrow(); + CommandSource.NewDraftGenesisReceipt receipt = + new CommandSource.NewDraftGenesisReceipt( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (row.get("game_design_version_row_id", Long.class) != target.gameDesignVersionRowId() + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_READBACK_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + return Optional.of(receipt); + } + + /** + * Applies command operations to private staged source. The returned evidence is one component of + * GAME_DESIGN_CONTROL_PLANE's combined APPLIED result; this method never records that result. + */ + public Optional apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + List mutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteControlPlaneScopes(binding, mutations, policyMutation); + Optional existing = application(binding); + if (existing.isPresent()) return existing; + if (mutations.isEmpty()) return Optional.empty(); + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireCoordinatorApplicationSlot(binding); + requireOwnerApplyStarted(binding); + + Record head = requireHead(target); + String expectedEpoch = commandScope(binding).expectedEpoch(); + if (!expectedEpoch.equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + } + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + requireVisibleHeadMatchesFence(target, inheritedCommitId); + String baselineDigest = head.get("baseline_digest", String.class); + List inheritedDefinitions; + if (inheritedCommitId == null) { + inheritedDefinitions = List.of(); + if (!"0".equals(expectedEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(expectedEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + inheritedDefinitions = inherited.definitions(); + } + for (CommandSource.Mutation mutation : mutations) + requireRevisionIdentityUnused(target, mutation); + String resultEpoch = new BigInteger(expectedEpoch).add(BigInteger.ONE).toString(); + CommandSnapshot snapshot = + new CommandSnapshot( + binding, + resultEpoch, + inheritedCommitId, + baselineDigest, + CommandSource.replay(inheritedDefinitions, mutations)); + CommandApplication result = + new CommandApplication(binding, inheritedCommitId, expectedEpoch, mutations, snapshot); + insertApplication(result, baselineDigest); + insertOperations(result); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM ?", + resultEpoch, + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + expectedEpoch, + inheritedCommitId); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + return Optional.of( + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_READBACK_FAILED"))); + } + + /** + * Makes the staged complete source visible only after the coordinator's exact synchronized fence + * and combined owner outcome are durable in this same transaction. + */ + public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + Optional existing = readSnapshot(target, binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + return existing.orElseThrow(); + } + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireExactSynchronizedOwnerResult(binding); + Record head = requireHead(target); + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + String baselineDigest = head.get("baseline_digest", String.class); + String sourceEpoch = head.get("source_epoch", String.class); + List mutations = CommandSource.mutations(binding); + requireCompleteControlPlaneScopes( + binding, mutations, CommandSource.hasRealmPolicyRevision(binding)); + List definitions; + if (!mutations.isEmpty()) { + CommandApplication applied = + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_UNAVAILABLE")); + if (!applied.snapshot().sourceEpoch().equals(sourceEpoch) + || !applied.snapshot().genesisReceiptDigest().equals(baselineDigest) + || !Objects.equals(applied.inheritedCommitId(), inheritedCommitId)) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_NOT_CURRENT"); + } + definitions = applied.snapshot().definitions(); + } else if (inheritedCommitId == null) { + if (!"0".equals(sourceEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + definitions = List.of(); + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(sourceEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + definitions = inherited.definitions(); + } + CommandSnapshot snapshot = + new CommandSnapshot(binding, sourceEpoch, inheritedCommitId, baselineDigest, definitions); + dsl.execute( + "INSERT INTO game_design_command_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, source_epoch, snapshot_json, snapshot_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + inheritedCommitId, + baselineDigest, + sourceEpoch, + snapshot.canonicalJson(), + snapshot.digest()); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET visible_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM ? AND source_epoch = ?", + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + inheritedCommitId, + sourceEpoch); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CONFLICT"); + return readSnapshot(target, binding.commitId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_READBACK_FAILED")); + } + + /** Captures source against the actual original publication operation and exact selected fence. */ + public CommandSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + lockAuthority(target); + Optional existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireOpenDraft(target); + Record selected = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selected == null + || !selection.canonicalJson().equals(selected.get("selection_json", String.class)) + || !selection.digest().equals(selected.get("selection_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_UNAVAILABLE"); + } + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow( + () -> + new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_UNAVAILABLE")); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_SEALED"); + } + Record versionRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()), + "COMMAND_SOURCE_VERSION_UNAVAILABLE"); + Long versionEpoch = versionRow.get("version_state_epoch", Long.class); + if (versionEpoch == null + || !selection.intent().expectedVersionStateEpoch().equals(Long.toString(versionEpoch))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_VERSION_EPOCH_CHANGED"); + } + DraftCommitBinding selectedCommit = selection.selectedCommit(); + requireCurrentFence(selectedCommit); + CommandSnapshot snapshot = + readSnapshot(target, selectedCommit.commitId()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SELECTED_SNAPSHOT_UNAVAILABLE")); + Record head = requireHead(target); + if (!selectedCommit.equals(snapshot.binding()) + || !selectedCommit.commitId().equals(head.get("visible_commit_id", UUID.class)) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_SOURCE_NOT_SYNCHRONIZED"); + } + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_command_source_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, " + + "operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + selectedCommit.commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_READBACK_FAILED")); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_snapshot WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.binding().digest().equals(row.get("input_digest", String.class)) + || !snapshot.binding().canonicalJson().equals(row.get("binding_json", String.class)) + || !snapshot.sourceEpoch().equals(row.get("source_epoch", String.class)) + || !snapshot.genesisReceiptDigest().equals(row.get("baseline_digest", String.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_STORAGE_CONFLICT"); + } + var commit = + new DraftCommitCoordinatorRepository(dsl) + .read(target, snapshot.binding().requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + Record fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (!commit.binding().equals(snapshot.binding()) + || fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyDefinitionProvenance(snapshot); + return Optional.of(snapshot); + } + + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !selection.selectedCommit().commitId().equals(row.get("commit_id", UUID.class))) { + throw new IllegalArgumentException("COMMAND_SOURCE_FREEZE_OPERATION_CONFLICT"); + } + CommandSnapshot snapshot = + readSnapshot(target, row.get("commit_id", UUID.class)) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_SNAPSHOT_UNAVAILABLE")); + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + private void insertApplication(CommandApplication application, String baselineDigest) { + DraftCommitBinding binding = application.binding(); + dsl.execute( + "INSERT INTO game_design_command_source_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, expected_epoch, snapshot_json, " + + "operations_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + application.inheritedCommitId(), + baselineDigest, + application.expectedEpoch(), + application.snapshot().canonicalJson(), + CommandSource.mutationsJson(application.mutations()), + application.canonicalBytes()); + } + + private void insertOperations(CommandApplication application) { + for (CommandSource.Mutation mutation : application.mutations()) { + String operationJson = CommandSource.canonical(mutation.canonicalObject()); + dsl.execute( + "INSERT INTO game_design_command_source_operation " + + "(canonical_tenant_id, canonical_version_id, commit_id, revision_order, revision_id, " + + "operation_kind, command_id, command_key, definition_json, operation_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + application.binding().target().canonicalTenantId(), + application.binding().target().canonicalVersionId(), + application.binding().commitId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.revisionId(), + mutation.operation().name(), + mutation.commandId(), + mutation.stableKey(), + mutation.definitionJson(), + operationJson); + } + } + + private Optional application(DraftCommitBinding binding) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_application WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + DraftCommitBinding stored = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + String operationsJson = row.get("operations_json", String.class); + List mutations = CommandSource.mutationsFromStored(operationsJson); + CommandApplication result = + new CommandApplication( + stored, + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + mutations, + snapshot); + if (!stored.equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !CommandSource.mutationsJson(mutations).equals(operationsJson) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_EXACT_BINDING_CONFLICT"); + } + List storedOperations = + dsl.fetch( + "SELECT operation_json FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("operation_json", String.class); + if (!storedOperations.equals( + result.mutations().stream() + .map(m -> CommandSource.canonical(m.canonicalObject())) + .toList())) { + throw new IllegalStateException("COMMAND_SOURCE_OPERATION_READBACK_CONFLICT"); + } + return Optional.of(result); + } + + private void verifyDefinitionProvenance(CommandSnapshot snapshot) { + for (CommandSource.Definition definition : snapshot.definitions()) { + Record row = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + definition.sourceCommitId()); + if (row == null) + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_COMMIT_UNAVAILABLE"); + DraftCommitBinding original = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!original.target().equals(snapshot.binding().target())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_TARGET_CHANGED"); + } + CommandSource.Mutation source = + CommandSource.mutations(original).stream() + .filter(mutation -> mutation.revisionId().equals(definition.sourceRevisionId())) + .filter(mutation -> mutation.operation() == CommandSource.OperationKind.UPSERT) + .findFirst() + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_AUTHORED_REVISION_UNAVAILABLE")); + if (!source.commandId().equals(definition.commandId()) + || !source.definitionJson().equals(definition.definitionJson()) + || !source.commitId().equals(definition.sourceCommitId())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_PROVENANCE_CHANGED"); + } + } + } + + private void requireCompleteControlPlaneScopes( + DraftCommitBinding binding, + List commandMutations, + boolean policyMutation) { + List units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream().filter(this::isCommandScope).toList(); + List policies = + units.stream().filter(this::isPolicyScope).toList(); + if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) + || policies.size() != (policyMutation ? 1 : 0) + || commands.size() + policies.size() != units.size()) { + throw new IllegalArgumentException( + "Complete supported Game Design control-plane scopes are required"); + } + if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); + if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); + } + + private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private boolean isPolicyScope(DraftCommitBinding.AffectedUnit unit) { + return RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId()); + } + + private void requireScopeTarget(DraftCommitBinding.AffectedUnit unit, TargetProof target) { + if (!target.canonicalVersionId().toString().equals(unit.aggregateId())) { + throw new IllegalArgumentException( + "Control-plane scope must bind the exact canonical Version"); + } + } + + private DraftCommitBinding.AffectedUnit commandScope(DraftCommitBinding binding) { + return binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(this::isCommandScope) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("Command source affected scope is omitted")); + } + + private void requireCoordinatorApplicationSlot(DraftCommitBinding binding) { + var slot = + new DraftCommitCoordinatorRepository(dsl) + .readApplicationSlot(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_CHANGED"); + } + } + + private void requireOwnerApplyStarted(DraftCommitBinding binding) { + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != OwnerStatus.IN_PROGRESS && state.status() != OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("COMMAND_SOURCE_OWNER_APPLICATION_NOT_STARTED"); + } + } + + private void requireExactSynchronizedOwnerResult(DraftCommitBinding binding) { + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + var commit = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + var owner = commit.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!commit.binding().equals(binding) + || commit.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED + || !binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + if (binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE) + && (owner == null + || owner.status() != OwnerStatus.APPLIED + || owner.outcome().isEmpty() + || !binding.commitId().equals(owner.outcome().orElseThrow().commitId()) + || !binding.digest().equals(owner.outcome().orElseThrow().bindingDigest()))) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + } + + private void requireVisibleHeadMatchesFence(TargetProof target, UUID visibleCommitId) { + var fence = new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target); + if (visibleCommitId == null) { + if (fence.isPresent()) + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } else if (fence.isEmpty() || !visibleCommitId.equals(fence.orElseThrow().commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } + } + + private void requireCurrentFence(DraftCommitBinding binding) { + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE")); + if (!binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_COMMIT_NOT_CURRENT"); + } + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + if (!retained.binding().equals(binding)) { + throw new IllegalArgumentException("COMMAND_SOURCE_COMMIT_BINDING_CONFLICT"); + } + } + + private void requireRevisionIdentityUnused(TargetProof target, CommandSource.Mutation mutation) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + mutation.revisionId()) + != null) { + throw new IllegalArgumentException("COMMAND_SOURCE_REVISION_ID_REUSE"); + } + } + + private Optional baseline(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_baseline WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Optional head(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Record requireHead(TargetProof target) { + return head(target) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_BASELINE_UNAVAILABLE")); + } + + private void requireHeadBaseline(TargetProof target, String digest) { + Record row = requireHead(target); + if (!digest.equals(row.get("baseline_digest", String.class)) + || !"0".equals(row.get("source_epoch", String.class)) + || row.get("visible_commit_id", UUID.class) != null + || row.get("applied_commit_id", UUID.class) != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_READBACK_CONFLICT"); + } + } + + private void requireVersionInsertWitness( + TargetProof target, String creationTransactionId, boolean requireCurrentTransaction) { + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ?", + target.gameDesignVersionRowId()); + Record currentTransaction = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_current_xact_id()::TEXT AS transaction_id"), + "COMMAND_SOURCE_CURRENT_TRANSACTION_UNAVAILABLE"); + String currentTransactionId = currentTransaction.get("transaction_id", String.class); + if (witness == null + || !creationTransactionId.equals(witness.get("creation_transaction_id", String.class)) + || (requireCurrentTransaction && !creationTransactionId.equals(currentTransactionId))) { + throw new IllegalStateException("COMMAND_SOURCE_NEW_DRAFT_INSERTION_WITNESS_UNAVAILABLE"); + } + } + + private void requireOpenDraft(TargetProof target) { + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_RESERVED"); + } + } + + private void lockAuthority(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.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.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + } + + private Record version(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.id, v.tenant_id, 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.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ?", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + return row; + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Command source writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java new file mode 100644 index 0000000000..45d095299a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.gamedesign.publication; + +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed original operation input. Codec validation supplies integrity, never authorization. */ +public record GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; + + public GameDesignPublicationOperation { + var binding = new GameDesignPublicationOperationBinding(account, world); + account = binding.account(); + world = binding.world(); + } + + public byte[] canonicalBytes() { + return new GameDesignPublicationOperationBinding(account, world).canonicalBytes(); + } + + public static GameDesignPublicationOperation fromStored(byte[] bytes) { + var binding = GameDesignPublicationOperationBinding.fromStored(bytes); + return new GameDesignPublicationOperation(binding.account(), binding.world()); + } + + public String workflowId() { + return world.request().publishWorkflowId(); + } + + public String tenantKey() { + return account.input().selection().target().gameDesignVersionTenantKey(); + } + + public long versionId() { + return account.input().selection().target().gameDesignVersionRowId(); + } + + public String selectionDigest() { + return account.input().selection().digest(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java new file mode 100644 index 0000000000..da6f3ddb2f --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner storage only. Deliberately has no runtime bean or authenticated ingress. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class GameDesignPublicationOperationRepository { + // Keep this v1 projection fixed: its keys and values reproduce the V50.12 release-row JSON + // byte-for-byte while remaining independent of columns added by later migrations. + private static final String RELEASE_ROW_EVIDENCE_V1 = + "jsonb_build_object(" + + "'artifact_digests_json', r.artifact_digests_json, " + + "'attestation_schema_version', r.attestation_schema_version, " + + "'canonical_tenant_id', r.canonical_tenant_id, " + + "'canonical_version_id', r.canonical_version_id, " + + "'command_definitions_json', r.command_definitions_json, " + + "'generation_config_revision', r.generation_config_revision, " + + "'id', r.id, " + + "'manifest_hash', r.manifest_hash, " + + "'manifest_schema_version', r.manifest_schema_version, " + + "'participant_digests_json', r.participant_digests_json, " + + "'publish_workflow_id', r.publish_workflow_id, " + + "'published_at', r.published_at, " + + "'published_release_bundle_ref', r.published_release_bundle_ref, " + + "'required_manifest_asset_keys_json', r.required_manifest_asset_keys_json, " + + "'script_only', r.script_only, " + + "'script_patch_version', r.script_patch_version, " + + "'tenant_id', r.tenant_id, " + + "'version_id', r.version_id, " + + "'version_number', r.version_number, " + + "'world_published_start_location_evidence_json', r.world_published_start_location_evidence_json" + + ")::TEXT"; + + private final DSLContext dsl; + + public GameDesignPublicationOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public void reserve(GameDesignPublicationOperation operation) { + requireTransaction(); + lock(operation.tenantKey(), operation.workflowId(), operation.versionId()); + Optional existing = read(operation.workflowId()); + if (existing.isPresent()) { + exact(existing.get().operation(), operation); + return; + } + dsl.execute( + "INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), + operation.tenantKey(), + operation.versionId(), + operation.selectionDigest(), + operation.canonicalBytes()); + } + + /** Caller has already proved authorization; reservation and source freeze are one transaction. */ + public GameDesignSourceRepository.Capture reserveSourceBacked( + GameDesignPublicationOperation operation) { + reserve(operation); + return new GameDesignSourceRepository(dsl).freeze(operation); + } + + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return new GameDesignSourceRepository(dsl).readCapture(operation); + } + + public GameDesignPublicationOperation requirePending( + String tenant, String workflow, long version, String digest) { + requireTransaction(); + lock(tenant, workflow, version); + Readback result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !result.outcome().equals("PENDING")) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + return operation; + } + + public void seal(String tenant, String workflow, long version, String digest, boolean published) { + GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); + Record release = + dsl.fetchOne( + "SELECT r.*, " + + RELEASE_ROW_EVIDENCE_V1 + + " AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + tenant, + version); + String evidence = release == null ? null : release.get("evidence", String.class); + if (published != (evidence != null)) + throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); + String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; + byte[] result = receipt(operation, outcome, evidence); + Long publicationEpoch = null; + if (published) { + Record committedVersion = + dsl.fetchOne( + "SELECT version_state, version_state_epoch FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenant, + version); + if (committedVersion == null + || !"PUBLISHED".equals(committedVersion.get("version_state", String.class))) { + throw new IllegalStateException("PUBLICATION_VERSION_NOT_COMMITTED"); + } + publicationEpoch = committedVersion.get("version_state_epoch", Long.class); + } + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.valueOf(outcome), + published ? PublicationReleaseContent.fromRow(release) : null, + publicationEpoch); + int changed = + dsl.execute( + "UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", + outcome, + result, + evidence, + terminal.canonicalBytes(), + publicationEpoch, + published ? terminal.releaseContent().canonicalBytes() : null, + published ? terminal.publishedReleaseBundleDigest() : null, + workflow); + if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); + } + + public Optional read(String workflow) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", + workflow); + if (row == null) return Optional.empty(); + var operation = + GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); + String outcome = row.get("outcome", String.class); + byte[] bytes = row.get("result_bytes", byte[].class); + String evidence = row.get("release_row_json", String.class); + byte[] terminalBytes = row.get("terminal_evidence_bytes", byte[].class); + if (!operation.workflowId().equals(workflow) + || !operation.tenantKey().equals(row.get("tenant_id", String.class)) + || operation.versionId() != row.get("version_id", Long.class) + || !operation.selectionDigest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_OPERATION_STORAGE_CONFLICT"); + } + if (!"PENDING".equals(outcome)) { + if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) + throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); + Record release = + dsl.fetchOne( + "SELECT " + + RELEASE_ROW_EVIDENCE_V1 + + " AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + String actual = release == null ? null : release.get("evidence", String.class); + if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { + throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); + } + // V50 history remains readable but never acquires unverifiable forward evidence. + if (terminalBytes != null) { + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || !terminal.outcome().name().equals(outcome)) { + throw new IllegalStateException("PUBLICATION_TERMINAL_IDENTITY_CONFLICT"); + } + if (terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED) { + Record immutableRelease = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), + PublicationReleaseContent.fromRow(immutableRelease).canonicalBytes()) + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), + row.get("release_content_bytes", byte[].class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !terminal + .publishedReleaseBundleDigest() + .equals(row.get("published_release_bundle_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_TERMINAL_BACKING_CONFLICT"); + } + } + } + Record attempt = + dsl.fetchOne( + "SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); + if (attempt == null) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + String attemptStatus = attempt.get("status", String.class); + if (!("PUBLISHED".equals(outcome) ? "SUCCEEDED" : "FAILED").equals(attemptStatus)) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + } + return Optional.of(new Readback(operation, outcome, bytes, terminalBytes)); + } + + private void lock(String tenant, String workflow, long version) { + if (dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", tenant) == null + || dsl.fetchOne( + "SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", + tenant, + workflow, + version) + == null + || dsl.fetchOne( + "SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) + == null) { + throw new IllegalStateException("PUBLICATION_OWNER_IDENTITY_UNAVAILABLE"); + } + } + + public static void exact( + GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { + if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + + private static byte[] receipt( + GameDesignPublicationOperation operation, String outcome, String evidence) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + if (evidence == null) { + DraftAuthorizationFenceBinding.frame(out, new byte[0]); + } else { + DraftAuthorizationFenceBinding.frame(out, evidence); + } + return out.toByteArray(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Publication owner transaction required"); + } + + public record Readback( + GameDesignPublicationOperation operation, + String outcome, + byte[] receiptBytes, + byte[] terminalEvidenceBytes) { + public Readback { + receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); + terminalEvidenceBytes = terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + public Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + this(operation, outcome, receiptBytes, null); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + @Override + public byte[] receiptBytes() { + return receiptBytes == null ? null : receiptBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java new file mode 100644 index 0000000000..f0a5f87a14 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit local seam; upstream authentication/current authority must be established separately. + */ +public final class GameDesignPublicationOperationService { + private final GameDesignPublicationOperationRepository repository; + private final TransactionTemplate write; + private final TransactionTemplate read; + + public GameDesignPublicationOperationService( + GameDesignPublicationOperationRepository repository, + PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + write = new TransactionTemplate(transactions); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation( + GameDesignPublicationOperation operation) { + requireIndependent(); + var retained = readExact(operation); + if (retained.isPresent()) { + var original = retained.orElseThrow(); + if ("PENDING".equals(original.outcome())) { + read.executeWithoutResult( + status -> + repository + .readSourceCapture(operation) + .orElseThrow( + () -> new IllegalStateException("PUBLICATION_SOURCE_CAPTURE_UNAVAILABLE"))); + } + return original; + } + write.executeWithoutResult(status -> repository.reserveSourceBacked(operation)); + return readExact(operation) + .orElseThrow(() -> new IllegalStateException("Publication operation readback absent")); + } + + public Optional readExact( + GameDesignPublicationOperation operation) { + requireIndependent(); + return read.execute( + status -> + repository + .read(operation.workflowId()) + .map( + result -> { + GameDesignPublicationOperationRepository.exact(result.operation(), operation); + return result; + })); + } + + private static void requireIndependent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Independent publication read/write boundary required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..db79f0682e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Standalone authenticated read adapter. Deliberately has no runtime registration. */ +public final class GameDesignPublicationTerminalReadGrpcService + extends GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase { + private final GameDesignPublicationOperationService owner; + private final String namespace; + + public GameDesignPublicationTerminalReadGrpcService( + GameDesignPublicationOperationService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readGameDesignPublicationTerminal( + ReadGameDesignPublicationTerminalRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (peer == null + || !(peer.uri().equals(prefix + "account-service") + || peer.uri().equals(prefix + "world-management-service")) + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Account or World workload without end-user context required"); + return; + } + final ReadRequest request; + try { + request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail( + observer, + Status.INVALID_ARGUMENT, + "Complete canonical publication terminal read request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail( + observer, + Status.PERMISSION_DENIED, + "Terminal read namespace differs from authenticated peer"); + return; + } + final ReadResult result; + final ReadGameDesignPublicationTerminalResponse response; + try { + var operation = GameDesignPublicationOperation.fromStored(request.operationBytes()); + // readExact owns the independent read-only REPEATABLE_READ transaction and exact binding. + var stored = owner.readExact(operation); + if (stored.isEmpty() || stored.orElseThrow().outcome().equals("PENDING")) { + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()); + } else { + byte[] bytes = stored.orElseThrow().terminalEvidenceBytes(); + if (bytes == null) + throw new IllegalStateException("Historical terminal result has no captured evidence"); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(bytes); + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.valueOf( + stored.orElseThrow().outcome()), + Optional.of(terminal)); + } + response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + } catch (org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException + | org.jooq.exception.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "Publication terminal owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException conflict) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Retained publication terminal evidence unavailable or inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Publication terminal owner read failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java new file mode 100644 index 0000000000..e7c3ab067a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -0,0 +1,331 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseEvidence; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import org.jooq.DSLContext; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Joins the two actual Game Design sources under one caller-owned coordinator transaction. */ +public final class GameDesignSourceRepository { + private final DSLContext dsl; + private final RealmPolicySourceRepository policies; + private final CommandSourceRepository commands; + private final DraftCommitCoordinatorRepository coordinator; + + public GameDesignSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + policies = new RealmPolicySourceRepository(dsl); + commands = new CommandSourceRepository(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + /** + * Claim the exact reviewed proposal against actual owner evidence before any source dispatch. + * Account authorization and current permission through commit remain caller obligations. + */ + public DraftCommitCoordinatorRepository.CommitSnapshot claimReviewed( + DraftCommitBinding binding, GameDesignReviewedBaseEvidence reviewedEvidence) { + requireWrite(); + return new GameDesignReviewedBaseRepository(dsl).claimReviewed(binding, reviewedEvidence); + } + + /** Call only on the actual new full-Draft Version insertion branch, in that transaction. */ + public Genesis enrollFreshDraft(TargetProof target) { + requireWrite(); + Objects.requireNonNull(target, "target"); + RealmPolicyGenesis policy = policies.recordFreshGenesis(target); + CommandSource.NewDraftGenesisReceipt command = + commands.enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + target, policy.receiptId(), policy.creationTransactionId())); + Genesis result = new Genesis(policy, command); + if (!result.equals( + readGenesis(target) + .orElseThrow( + () -> + new IllegalStateException( + "GAME_DESIGN_SOURCE_GENESIS_READBACK_UNAVAILABLE")))) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_READBACK_CONFLICT"); + } + return result; + } + + public Optional readGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + var policy = policies.readGenesis(target); + var command = commands.readNewDraftGenesis(target); + if (policy.isEmpty() && command.isEmpty()) return Optional.empty(); + if (policy.isEmpty() || command.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + return Optional.of(new Genesis(policy.orElseThrow(), command.orElseThrow())); + } + + /** Stage actual source writes and record exactly one complete local owner outcome. */ + public Application apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + List commandMutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation); + requireGenesis(binding.target()); + requireReviewed(binding); + Optional command = commands.apply(binding); + if (command.isPresent() != !commandMutations.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_COMMAND_APPLICATION_INCOMPLETE"); + } + Optional policy = Optional.empty(); + if (policyMutation) { + // The policy-only path retains its existing exact owner result. Mixed input stages policy + // first, then records the combined result using the command store's actual readback bytes. + policy = + Optional.of( + command.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); + } + OwnerOutcome expected; + if (policy.isPresent() && command.isPresent()) { + var policyResult = policy.orElseThrow(); + var commandResult = command.orElseThrow(); + List epochs = + List.of( + commandResult.commandAppliedEpoch(), + policyResult.ownerOutcome().appliedEpochs().getFirst()); + policies.recordCombinedOwnerOutcome(binding, commandResult.canonicalBytes(), epochs); + expected = policyResult.combinedOwnerOutcome(commandResult.canonicalBytes(), epochs); + } else if (policy.isPresent()) { + expected = policy.orElseThrow().ownerOutcome(); + } else { + CommandApplication commandResult = command.orElseThrow(); + expected = commandOnlyOutcome(binding, commandResult); + coordinator.recordOwnerOutcome(binding, expected); + } + OwnerOutcome retained = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("GAME_DESIGN_COMMIT_READBACK_UNAVAILABLE")) + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome() + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_UNAVAILABLE")); + if (!expected.equals(retained)) { + throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); + } + return new Application(binding, command, policy, retained); + } + + /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ + public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + requireGenesis(binding.target()); + requireReviewed(binding); + CommandSnapshot command = commands.captureSynchronized(binding); + RealmPolicySnapshot policy = policies.captureSynchronized(binding); + if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); + } + return new SynchronizedSources(command, policy); + } + + /** Freeze both complete, selected source snapshots against the same retained operation. */ + public Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + requireGenesis(operation.account().input().selection().target()); + requireReviewed(operation.account().input().selection().selectedCommit()); + RealmPolicySnapshot.Capture policy; + try { + policy = policies.freeze(operation); + } catch (RealmPolicySource.InvalidPublicationPolicySetException failure) { + throw new PublishGateFailureException( + PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET, + "A full Version requires 1 through 128 realm policies with exactly one visible public-production realm"); + } + CommandSnapshot.Capture command = commands.freeze(operation); + Capture result = new Capture(command, policy); + Capture retained = + readCapture(operation) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_UNAVAILABLE")); + if (!Arrays.equals(result.command().canonicalBytes(), retained.command().canonicalBytes()) + || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); + } + return retained; + } + + /** Exact stored captures for a bundle producer; partial capture cannot authorize publication. */ + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + requireReviewed(operation.account().input().selection().selectedCommit()); + var command = commands.readCapture(operation); + var policy = policies.readCapture(operation); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); + } + return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow())); + } + + public Optional readSynchronized(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + var command = commands.readSnapshot(target, commitId); + var policy = policies.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); + } + return Optional.of(new SynchronizedSources(command.orElseThrow(), policy.orElseThrow())); + } + + private void requireGenesis(TargetProof target) { + if (readGenesis(target).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + } + + private void requireReviewed(DraftCommitBinding binding) { + new GameDesignReviewedBaseRepository(dsl).requireRetained(binding); + } + + private static OwnerOutcome commandOnlyOutcome( + DraftCommitBinding binding, CommandApplication command) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-command-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, command.canonicalBytes()); + return new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + command.resultIdentity(), + out.toByteArray(), + List.of(command.commandAppliedEpoch())); + } + + private static void requireCompleteScopes( + DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy) { + if (!hasCommand && !hasPolicy + || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { + throw new IllegalArgumentException("Game Design owner requires typed source revisions"); + } + List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream() + .filter( + unit -> + CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId())) + .toList(); + List policies = + units.stream() + .filter( + unit -> + RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId())) + .toList(); + if (commands.size() != (hasCommand ? 1 : 0) + || policies.size() != (hasPolicy ? 1 : 0) + || commands.size() + policies.size() != units.size() + || units.stream() + .anyMatch( + unit -> + !binding.target().canonicalVersionId().toString().equals(unit.aggregateId()))) { + throw new IllegalArgumentException("Complete supported Game Design source scopes required"); + } + if (hasPolicy) { + binding.revisions().stream() + .filter(revision -> revision.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .forEach(revision -> RealmPolicySource.mutation(binding, revision)); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Game Design source writes require caller-owned writable READ_COMMITTED transaction"); + } + } + + public record Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + public Genesis { + Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(command, "command"); + if (!policy.target().equals(command.target()) + || !policy.receiptId().equals(command.receiptId()) + || !policy.creationTransactionId().equals(command.creationTransactionId())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); + } + } + } + + public record Application( + DraftCommitBinding binding, + Optional command, + Optional policy, + OwnerOutcome ownerOutcome) { + public Application { + Objects.requireNonNull(binding, "binding"); + command = Objects.requireNonNull(command, "command"); + policy = Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(ownerOutcome, "ownerOutcome"); + if (command.isEmpty() && policy.isEmpty() + || command.isPresent() && !binding.equals(command.orElseThrow().binding()) + || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) + || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE + || ownerOutcome.status() != OwnerStatus.APPLIED + || !binding.commitId().equals(ownerOutcome.commitId()) + || !binding.digest().equals(ownerOutcome.bindingDigest())) { + throw new IllegalArgumentException("Owner application differs from exact Draft binding"); + } + } + } + + public record SynchronizedSources(CommandSnapshot command, RealmPolicySnapshot policy) { + public SynchronizedSources { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!command.binding().equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + } + } + + public record Capture(CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy) { + public Capture { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) + || !command.snapshot().binding().equals(policy.snapshot().binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); + } + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java new file mode 100644 index 0000000000..e330e02684 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; + +/** Maps the actual immutable release row, never a launch descriptor or a mutable Version read. */ +final class PublicationReleaseContent { + private PublicationReleaseContent() {} + + static GameDesignPublicationTerminalEvidence.ReleaseContent fromRow(Record row) { + if (row == null + || !Boolean.FALSE.equals(row.get("script_only", Boolean.class)) + || row.get("script_patch_version", String.class) != null) { + throw new IllegalStateException("PUBLICATION_RELEASE_NOT_FULL_VERSION"); + } + var mapper = new ObjectMapper(); + List participants = + mapper.readValue( + row.get("participant_digests_json", String.class), new TypeReference<>() {}); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("published_release_bundle_ref", String.class), + row.get("version_number", Integer.class), + row.get("attestation_schema_version", String.class), + row.get("publish_workflow_id", String.class), + row.get("manifest_hash", String.class), + row.get("manifest_schema_version", Integer.class), + mapper.readValue( + row.get("artifact_digests_json", String.class), + new TypeReference>() {}), + mapper.readValue( + row.get("required_manifest_asset_keys_json", String.class), + new TypeReference>() {}), + participants.stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(), + mapper.readValue( + row.get("command_definitions_json", String.class), + new TypeReference>() {}), + row.get("generation_config_revision", String.class), + WorldPublishedStartLocationEvidence.fromStored( + row.get("world_published_start_location_evidence_json", String.class) + .getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java new file mode 100644 index 0000000000..cb62ef5bbc --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; + +/** Actual owner application result, returned only after the atomic source write/readback. */ +public record RealmPolicyApplication( + RealmPolicyGenesis genesis, + UUID inheritedCommitId, + String expectedEpoch, + RealmPolicySnapshot snapshot) { + public RealmPolicyApplication( + UUID inheritedCommitId, String expectedEpoch, RealmPolicySnapshot snapshot) { + this(null, inheritedCommitId, expectedEpoch, snapshot); + } + + public RealmPolicyApplication { + if ((inheritedCommitId == null && genesis == null) + || new UUID(0, 0).equals(inheritedCommitId) + || (genesis != null && !genesis.target().equals(snapshot.binding().target())) + || expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) { + throw new IllegalArgumentException("Policy application must advance its exact source epoch"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(out, genesis == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, genesis == null ? new byte[0] : genesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inheritedCommitId == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public OwnerOutcome ownerOutcome() { + var binding = snapshot.binding(); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "realm-policy:" + binding.commitId(), + canonicalBytes(), + List.of( + new AppliedEpoch( + RealmPolicySource.SCOPE, + binding.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch, + snapshot.sourceEpoch()))); + } + + /** Parent composes actual sibling source evidence and its complete exact epoch vector once. */ + public OwnerOutcome combinedOwnerOutcome( + byte[] siblingEvidence, List completeEpochs) { + if (siblingEvidence == null || siblingEvidence.length == 0) { + throw new IllegalArgumentException("Actual sibling owner application evidence required"); + } + var binding = snapshot.binding(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, siblingEvidence); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "control-plane-source:" + binding.commitId(), + out.toByteArray(), + completeEpochs); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java new file mode 100644 index 0000000000..af88d5d246 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Empty new-Draft baseline receipt, distinct from every actual authored commit. */ +public record RealmPolicyGenesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public RealmPolicyGenesis { + if (target == null + || receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact persisted new-Draft genesis identity required"); + } + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-genesis/v1", + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId, + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java new file mode 100644 index 0000000000..9749791c25 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.dao.DataAccessException; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; + +/** Protected read adapter; the owner-read opt-in condition controls runtime registration. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.game-design.published-realm-entry-policy-read", + name = "enabled", + havingValue = "true") +public final class RealmPolicyPublicationGrpcService + extends PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase { + private final RealmPolicyPublicationService owner; + private final String namespace; + + public RealmPolicyPublicationGrpcService( + RealmPolicyPublicationService owner, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void resolvePublishedRealmEntryPolicy( + ResolvePublishedRealmEntryPolicyRequest wire, + StreamObserver observer) { + if (!requireGameSessionPeer(observer)) return; + + final PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest request; + try { + request = PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "Canonical schema-1 realm policy read required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED, "Realm policy target namespace differs from peer"); + return; + } + + final PublishedRealmEntryPolicySetEvidence evidence; + try { + Optional stored = + owner.readPublishedSet(request.canonicalTenantId(), request.canonicalVersionId()); + if (stored.isEmpty()) { + fail(observer, Status.NOT_FOUND, "Published realm policy set not found"); + return; + } + RealmPolicyPublishedEvidence.PublishedSet ownerSet = stored.orElseThrow(); + requireExactTarget( + request.canonicalTenantId(), request.canonicalVersionId(), ownerSet.target()); + evidence = RealmPolicyPublishedEvidenceMapper.toShared(ownerSet); + if (!containsSelector(evidence, request.worldSlug(), request.realmSlug())) { + fail(observer, Status.NOT_FOUND, "Published realm policy selector not found"); + return; + } + } catch (DataAccessException + | org.jooq.exception.DataAccessException + | TransactionException unavailable) { + fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy owner read failed"); + return; + } + + final ResolvePublishedRealmEntryPolicyResponse response; + try { + response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy response encoding failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest wire, + StreamObserver observer) { + if (!requireGameSessionPeer(observer)) return; + + final PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request; + try { + request = PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "Canonical schema-1 realm policy read required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED, "Realm policy target namespace differs from peer"); + return; + } + + final PublishedRealmEntryPolicySetEvidence evidence; + try { + Optional stored = + owner.readPublishedSet(request.canonicalTenantId(), request.canonicalVersionId()); + if (stored.isEmpty()) { + fail(observer, Status.NOT_FOUND, "Published realm policy set not found"); + return; + } + RealmPolicyPublishedEvidence.PublishedSet ownerSet = stored.orElseThrow(); + requireExactTarget( + request.canonicalTenantId(), request.canonicalVersionId(), ownerSet.target()); + evidence = RealmPolicyPublishedEvidenceMapper.toShared(ownerSet); + } catch (DataAccessException + | org.jooq.exception.DataAccessException + | TransactionException unavailable) { + fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy owner read failed"); + return; + } + + final ListPublishedRealmEntryPoliciesResponse response; + try { + response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy response encoding failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private boolean requireGameSessionPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + if (peer == null + || !peer.uri().equals(expectedPeer) + || !peer.namespace().equals(namespace) + || !peer.service().equals("game-session-service") + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Session workload without end-user context required"); + return false; + } + return true; + } + + private static boolean containsSelector( + PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { + return evidence.policies().stream() + .anyMatch( + policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug)); + } + + private static void requireExactTarget( + java.util.UUID tenantId, + java.util.UUID versionId, + net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof target) { + if (!target.canonicalTenantId().equals(tenantId) + || !target.canonicalVersionId().equals(versionId)) { + throw new IllegalStateException("Published policy owner returned a different target"); + } + } + + private static void fail(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java new file mode 100644 index 0000000000..cbfb3d6b90 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -0,0 +1,539 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal immutable policy association; all writes join the actual Game Design seal transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class RealmPolicyPublicationRepository { + private static final int MAX_POLICY_ROWS = RealmPolicySource.MAX_POLICIES; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final DSLContext dsl; + + public RealmPolicyPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Retains an association only from the operation's actual sealed PUBLISHED owner readback. Every + * full-Version publication requires its complete frozen policy capture. + */ + public Optional retainSealedPublished( + String publishWorkflowId) { + requireWrite(); + if (publishWorkflowId == null || publishWorkflowId.isBlank()) { + throw new IllegalArgumentException("Exact publication workflow required"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || operationReadback.terminalEvidenceBytes() == null) { + throw new IllegalStateException("POLICY_PUBLICATION_REQUIRES_SEALED_PUBLISHED_OPERATION"); + } + var operation = operationReadback.operation(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(operationReadback.terminalEvidenceBytes()); + if (!operation.workflowId().equals(publishWorkflowId) + || terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_BINDING_CONFLICT"); + } + TargetProof target = operation.account().input().selection().target(); + var sourceRepository = new RealmPolicySourceRepository(dsl); + Optional captureResult = sourceRepository.readCapture(operation); + if (captureResult.isEmpty()) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + } + var capture = captureResult.orElseThrow(); + if (!capture.operation().equals(operation) + || !capture.snapshot().binding().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_BINDING_CONFLICT"); + } + + var existing = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (existing != null) { + var retained = readPublishedSet(target, existing).orElseThrow(); + requireExactRetry(retained, operation, capture, terminal); + return Optional.of(retained); + } + + requireOwner(target, terminal, true); + requireCurrentVisibleSource(target, capture.snapshot()); + requireActualRelease(operation, terminal); + + var release = terminal.releaseContent(); + var rows = new ArrayList(); + for (RealmPolicySource.Policy source : capture.snapshot().policies()) { + UUID id = UUID.randomUUID(); + rows.add( + new RealmPolicyPublishedEvidence.Policy( + id, + source, + RealmPolicyPublishedEvidence.policyDigest( + id, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source))); + } + List orderedSources = + RealmPolicySource.ordered( + rows.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList()); + if (!orderedSources.equals(capture.snapshot().policies()) + || rows.size() != capture.snapshot().policies().size()) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_SET_CHANGED"); + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + rows); + + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, " + + "source_commit_id, source_epoch, target_proof_json, operation_bytes, capture_bytes, " + + "terminal_evidence_bytes, release_content_bytes, published_release_bundle_ref, " + + "published_release_bundle_digest, publish_workflow_id, manifest_hash, " + + "publication_version_state_epoch, policy_count, policy_set_digest, sealed) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + RealmPolicyPublishedEvidence.targetProofJson(target), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + release.canonicalBytes(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + rows.size(), + setDigest); + + for (int ordinal = 0; ordinal < rows.size(); ordinal++) { + var row = rows.get(ordinal); + var source = row.source(); + var policy = source.policy(); + dsl.execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + ordinal, + row.policyId(), + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + row.policyDigest(), + policy.visible(), + policy.publicProduction()); + } + int sealed = + dsl.execute( + "UPDATE game_design_published_realm_policy_set SET sealed = TRUE " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND sealed = FALSE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (sealed != 1) throw new IllegalStateException("POLICY_PUBLICATION_SET_SEAL_CONFLICT"); + + var stored = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (stored == null) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_READBACK_UNAVAILABLE"); + } + var readback = readPublishedSet(target, stored).orElseThrow(); + requireExactRetry(readback, operation, capture, terminal); + return Optional.of(readback); + } + + /** + * Caller supplies a REPEATABLE_READ snapshot; no caller state substitutes for stored evidence. + */ + public Optional readPublishedSet( + UUID canonicalTenantId, UUID canonicalVersionId) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Canonical policy target resolution requires one read-only REPEATABLE_READ snapshot"); + } + var version = + // Exact read uses the transaction-bound search path, not the migration-only lock API. + new VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId(canonicalTenantId, canonicalVersionId); + if (version.isEmpty()) return Optional.empty(); + var owner = version.orElseThrow(); + return readPublishedSet( + new TargetProof( + owner.getCanonicalTenantId(), + owner.getCanonicalVersionId(), + owner.getId(), + owner.getTenantId(), + owner.getIdentitySourceGameRowId(), + owner.getIdentitySourceGameTenantKey(), + owner.getIdentitySourceProvenanceKind())); + } + + /** Exact internal target read; the service owns its independent snapshot boundary. */ + public Optional readPublishedSet(TargetProof target) { + Objects.requireNonNull(target, "target"); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? Optional.empty() : readPublishedSet(target, row); + } + + private Optional readPublishedSet( + TargetProof target, Record header) { + if (!Boolean.TRUE.equals(header.get("sealed", Boolean.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_INCOMPLETE"); + } + if (!Objects.equals( + header.get("target_proof_json", String.class), + RealmPolicyPublishedEvidence.targetProofJson(target)) + || !Objects.equals( + header.get("canonical_tenant_id", UUID.class), target.canonicalTenantId()) + || !Objects.equals( + header.get("canonical_version_id", UUID.class), target.canonicalVersionId()) + || !Objects.equals( + header.get("game_design_version_row_id", Long.class), + target.gameDesignVersionRowId())) { + throw new IllegalStateException("POLICY_PUBLICATION_TARGET_PROOF_CONFLICT"); + } + + byte[] operationBytes = header.get("operation_bytes", byte[].class); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_TARGET_CONFLICT"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || !Arrays.equals(operationReadback.operation().canonicalBytes(), operationBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_NOT_SEALED"); + } + byte[] terminalBytes = operationReadback.terminalEvidenceBytes(); + byte[] retainedTerminalBytes = header.get("terminal_evidence_bytes", byte[].class); + if (terminalBytes == null || !Arrays.equals(terminalBytes, retainedTerminalBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_CHANGED"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + var release = terminal.releaseContent(); + if (!Arrays.equals(release.canonicalBytes(), header.get("release_content_bytes", byte[].class)) + || !Objects.equals( + release.publishedReleaseBundleRef(), + header.get("published_release_bundle_ref", String.class)) + || !Objects.equals( + terminal.publishedReleaseBundleDigest(), + header.get("published_release_bundle_digest", String.class)) + || !Objects.equals( + release.publishWorkflowId(), header.get("publish_workflow_id", String.class)) + || !Objects.equals(release.manifestHash(), header.get("manifest_hash", String.class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + header.get("publication_version_state_epoch", Long.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CHANGED"); + } + + Record version = requireOwner(target, terminal, false); + int versionNumber = header.get("version_number", Integer.class); + if (release.versionNumber() != versionNumber + || version.get("version_number", Integer.class) != versionNumber) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NUMBER_CHANGED"); + } + var sourceRepository = new RealmPolicySourceRepository(dsl); + var capture = + sourceRepository + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE")); + byte[] captureBytes = header.get("capture_bytes", byte[].class); + if (!Arrays.equals(capture.canonicalBytes(), captureBytes) + || !capture.snapshot().binding().target().equals(target) + || !Objects.equals( + capture.snapshot().binding().commitId(), header.get("source_commit_id", UUID.class)) + || !Objects.equals( + capture.snapshot().sourceEpoch(), header.get("source_epoch", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_CHANGED"); + } + requireCurrentVisibleSource(target, capture.snapshot()); + + int expectedCount = header.get("policy_count", Integer.class); + if (expectedCount < 1 || expectedCount > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_OVERSIZED_OR_EMPTY"); + } + List storedRows = + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "ORDER BY ordinal LIMIT ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + MAX_POLICY_ROWS + 1); + if (storedRows.size() != expectedCount || storedRows.size() > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_CARDINALITY_CONFLICT"); + } + List policies = new ArrayList<>(); + for (int ordinal = 0; ordinal < storedRows.size(); ordinal++) { + Record row = storedRows.get(ordinal); + RealmPolicySource.Policy source = sourcePolicy(row); + if (!Objects.equals(row.get("ordinal", Integer.class), ordinal)) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_ORDER_CONFLICT"); + } + policies.add( + new RealmPolicyPublishedEvidence.Policy( + row.get("realm_policy_id", UUID.class), + source, + row.get("policy_digest", String.class))); + } + List expectedPolicies = capture.snapshot().policies(); + if (!expectedPolicies.equals( + policies.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_ROWS_CHANGED"); + } + for (var policy : policies) { + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policy.policyId(), + target, + versionNumber, + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + policy.source()); + if (!digest.equals(policy.policyDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_POLICY_DIGEST_CONFLICT"); + } + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies); + if (!setDigest.equals(header.get("policy_set_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_DIGEST_CONFLICT"); + } + return Optional.of( + new RealmPolicyPublishedEvidence.PublishedSet( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + expectedCount, + setDigest, + policies)); + } + + private RealmPolicySource.Policy sourcePolicy(Record row) { + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical(row.get("policy_json", String.class), JSON); + if (!Objects.equals(row.get("world_slug", String.class), policy.worldSlug()) + || !Objects.equals(row.get("realm_slug", String.class), policy.realmSlug()) + || !Objects.equals(row.get("visible", Boolean.class), policy.visible()) + || !Objects.equals( + row.get("public_production", Boolean.class), policy.publicProduction())) { + throw new IllegalStateException("POLICY_PUBLICATION_TYPED_POLICY_CONFLICT"); + } + return new RealmPolicySource.Policy( + row.get("source_commit_id", UUID.class), + row.get("source_revision_id", UUID.class), + row.get("logical_revision_id", String.class), + policy); + } + + /** This reads without acquiring earlier publication locks; the seal already holds Version. */ + private Record requireOwner( + TargetProof target, GameDesignPublicationTerminalEvidence terminal, boolean atSeal) { + Record owner = + dsl.fetchOne( + "SELECT v.version_state, v.version_state_epoch, v.version_number, 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.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND g.id = ? AND g.tenant_id = ? AND g.canonical_tenant_id = ? " + + "AND g.tenant_identity_provenance_kind = ? AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.canonicalTenantId(), + target.sourceProvenanceKind()); + if (owner == null + || !Boolean.FALSE.equals(owner.get("is_script_only", Boolean.class)) + || owner.get("script_patch_version", String.class) != null + || owner.get("base_version_id", Long.class) != null) { + throw new IllegalStateException("POLICY_PUBLICATION_CANONICAL_OWNER_UNAVAILABLE"); + } + String state = owner.get("version_state", String.class); + long epoch = owner.get("version_state_epoch", Long.class); + if (atSeal) { + if (!"PUBLISHED".equals(state) || epoch != terminal.publicationVersionStateEpoch()) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_AT_SEAL"); + } + } else if (("PUBLISHED".equals(state) && epoch != terminal.publicationVersionStateEpoch()) + || ("ACTIVE".equals(state) && epoch <= terminal.publicationVersionStateEpoch()) + || (!"PUBLISHED".equals(state) && !"ACTIVE".equals(state))) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_CURRENT"); + } + return owner; + } + + private void requireCurrentVisibleSource(TargetProof target, RealmPolicySnapshot snapshot) { + Record source = + dsl.fetchOne( + "SELECT source_epoch, visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (source == null + || !Objects.equals(source.get("source_epoch", String.class), snapshot.sourceEpoch()) + || !Objects.equals( + source.get("visible_commit_id", UUID.class), snapshot.binding().commitId())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_VISIBILITY_CHANGED"); + } + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(target) + .orElseThrow( + () -> new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_UNAVAILABLE")); + if (!fence.commitId().equals(snapshot.binding().commitId()) + || !fence.requestId().equals(snapshot.binding().requestId()) + || !fence.inputDigest().equals(snapshot.binding().digest())) { + throw new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_CHANGED"); + } + } + + private void requireActualRelease( + GameDesignPublicationOperation operation, GameDesignPublicationTerminalEvidence terminal) { + Record row = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (row == null) throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_UNAVAILABLE"); + var release = PublicationReleaseContent.fromRow(row); + if (!Arrays.equals(release.canonicalBytes(), terminal.releaseContent().canonicalBytes()) + || !Objects.equals(row.get("publish_workflow_id", String.class), operation.workflowId()) + || !Objects.equals( + row.get("published_release_bundle_ref", String.class), + terminal.publishedReleaseBundleRef()) + || !Objects.equals(terminal.publishedReleaseBundleDigest(), release.contentDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CONFLICT"); + } + } + + private void requireExactRetry( + RealmPolicyPublishedEvidence.PublishedSet retained, + GameDesignPublicationOperation operation, + RealmPolicySnapshot.Capture capture, + GameDesignPublicationTerminalEvidence terminal) { + if (!Arrays.equals(retained.operationBytes(), operation.canonicalBytes()) + || !Arrays.equals(retained.captureBytes(), capture.canonicalBytes()) + || !Arrays.equals(retained.terminalEvidenceBytes(), terminal.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_IDENTITY_CONFLICT"); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Published policy association requires the owner READ_COMMITTED seal transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java new file mode 100644 index 0000000000..1af6a81893 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered internal API for binding a typed source capture to a sealed Game Design release. */ +public final class RealmPolicyPublicationService { + private final RealmPolicyPublicationRepository repository; + private final TransactionTemplate read; + + public RealmPolicyPublicationService( + RealmPolicyPublicationRepository repository, PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + read = new TransactionTemplate(Objects.requireNonNull(transactions)); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + /** + * Call immediately after the real PUBLISHED operation seal, inside the same owner transaction. + * The repository rereads the operation and its immutable terminal evidence before writing. + */ + public Optional retainSealedPublished( + String publishWorkflowId) { + return repository.retainSealedPublished(publishWorkflowId); + } + + /** Independent complete-set read; it never establishes runtime catalog or admission authority. */ + public Optional readPublishedSet( + UUID canonicalTenantId, UUID canonicalVersionId) { + requireIndependentRead(); + return read.execute( + status -> repository.readPublishedSet(canonicalTenantId, canonicalVersionId)); + } + + /** Internal complete-target read for owner composition, never caller-provided numeric aliases. */ + public Optional readPublishedSet(TargetProof target) { + requireIndependentRead(); + return read.execute(status -> repository.readPublishedSet(target)); + } + + /** Exact selector lookup over the independently verified complete set. */ + public Optional readPublishedPolicy( + TargetProof target, String worldSlug, String realmSlug) { + if (!net.firedevops.firemud.common.publication.RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !net.firedevops.firemud.common.publication.RealmEntryPolicy.isCanonicalSlug(realmSlug)) { + throw new IllegalArgumentException("Canonical realm policy selectors required"); + } + return readPublishedSet(target) + .flatMap( + set -> + set.policies().stream() + .filter( + policy -> + policy.source().policy().worldSlug().equals(worldSlug) + && policy.source().policy().realmSlug().equals(realmSlug)) + .findFirst()); + } + + private static void requireIndependentRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Published policy readback requires an independent REPEATABLE_READ transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java new file mode 100644 index 0000000000..e0432cb2f3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; + +/** Immutable internal evidence associating a frozen source set with its actual sealed release. */ +public final class RealmPolicyPublishedEvidence { + public static final String SET_DIGEST_SCHEMA = + PublishedRealmEntryPolicySetEvidence.SET_DIGEST_SCHEMA; + public static final String POLICY_DIGEST_SCHEMA = + PublishedRealmEntryPolicySetEvidence.POLICY_DIGEST_SCHEMA; + + private RealmPolicyPublishedEvidence() {} + + /** One Game Design allocated immutable identity for one effective authored policy. */ + public record Policy(UUID policyId, RealmPolicySource.Policy source, String policyDigest) { + public Policy { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical policy digest required"); + } + } + } + + /** Complete immutable set and the original owner evidence that authorized its publication. */ + public record PublishedSet( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public PublishedSet { + Objects.requireNonNull(target, "target"); + nonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0 + || sourceEpoch == null + || !sourceEpoch.matches("0|[1-9][0-9]*") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !digest(publishedReleaseBundleDigest) + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || !digest(manifestHash) + || publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Complete publication-bound policy identity required"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 + || policyCount > RealmPolicySource.MAX_POLICIES + || policyCount != policies.size() + || !digest(policySetDigest)) { + throw new IllegalArgumentException("Complete bounded policy-set evidence required"); + } + RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target) + || !operation.workflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException("Publication evidence differs from exact TargetProof"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + var release = terminal.releaseContent(); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes) + || !release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + if (!computePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof PublishedSet that)) return false; + return versionNumber == that.versionNumber + && publicationVersionStateEpoch == that.publicationVersionStateEpoch + && policyCount == that.policyCount + && Objects.equals(target, that.target) + && Objects.equals(sourceCommitId, that.sourceCommitId) + && Objects.equals(sourceEpoch, that.sourceEpoch) + && Objects.equals(publishedReleaseBundleRef, that.publishedReleaseBundleRef) + && Objects.equals(publishedReleaseBundleDigest, that.publishedReleaseBundleDigest) + && Objects.equals(publishWorkflowId, that.publishWorkflowId) + && Objects.equals(manifestHash, that.manifestHash) + && Arrays.equals(operationBytes, that.operationBytes) + && Arrays.equals(captureBytes, that.captureBytes) + && Arrays.equals(terminalEvidenceBytes, that.terminalEvidenceBytes) + && Objects.equals(policySetDigest, that.policySetDigest) + && Objects.equals(policies, that.policies); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + policyCount, + policySetDigest, + policies); + result = 31 * result + Arrays.hashCode(operationBytes); + result = 31 * result + Arrays.hashCode(captureBytes); + result = 31 * result + Arrays.hashCode(terminalEvidenceBytes); + return result; + } + + @Override + public String toString() { + return "PublishedSet[target=" + + target + + ", sourceCommitId=" + + sourceCommitId + + ", sourceEpoch=" + + sourceEpoch + + ", policyCount=" + + policyCount + + ", policySetDigest=" + + policySetDigest + + "]"; + } + } + + public static String targetProofJson(DraftCommitBinding.TargetProof target) { + return PublishedRealmEntryPolicySetEvidence.targetProofJson(target); + } + + public static String policyDigest( + UUID policyId, + DraftCommitBinding.TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + RealmPolicySource.Policy source) { + Objects.requireNonNull(source, "source"); + return PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + source.policy()); + } + + public static String computePolicySetDigest( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + var shared = + policies.stream() + .map( + policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) + .toList(); + return PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + shared); + } + + private static byte[] nonEmptyCopy(byte[] bytes, String name) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return bytes.clone(); + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static void nonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + name + " required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java new file mode 100644 index 0000000000..ac368131db --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; + +/** Pure mapping from the verified Game Design owner result into the shared sealed-set carrier. */ +final class RealmPolicyPublishedEvidenceMapper { + private RealmPolicyPublishedEvidenceMapper() {} + + static PublishedRealmEntryPolicySetEvidence toShared( + RealmPolicyPublishedEvidence.PublishedSet source) { + Objects.requireNonNull(source, "source"); + var policies = + source.policies().stream() + .map( + policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) + .toList(); + var candidate = + new PublishedRealmEntryPolicySetEvidence( + source.target(), + source.versionNumber(), + source.sourceCommitId(), + source.sourceEpoch(), + source.publishedReleaseBundleRef(), + source.publishedReleaseBundleDigest(), + source.publishWorkflowId(), + source.manifestHash(), + source.publicationVersionStateEpoch(), + source.operationBytes(), + source.captureBytes(), + source.terminalEvidenceBytes(), + source.policyCount(), + source.policySetDigest(), + policies); + return PublishedRealmEntryPolicySetEvidence.fromStored(candidate.canonicalBytes()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java new file mode 100644 index 0000000000..a024a75b5a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective source at one synchronized fence, including original revision provenance. */ +public record RealmPolicySnapshot( + DraftCommitBinding binding, String sourceEpoch, List policies) { + public RealmPolicySnapshot { + if (binding == null || sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact source binding and canonical epoch required"); + } + policies = RealmPolicySource.draftOrdered(policies); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "policies", + RealmPolicySource.tree(RealmPolicySource.policiesJson(policies)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public static RealmPolicySnapshot fromStored(String json) { + var node = RealmPolicySource.tree(json); + RealmPolicySource.fields( + node, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!"game-design-realm-policy-snapshot/v1".equals(RealmPolicySource.text(node, "schema"))) { + throw new IllegalArgumentException("Unsupported policy snapshot schema"); + } + var result = + new RealmPolicySnapshot( + DraftCommitBinding.fromStored( + RealmPolicySource.text(node, "bindingJson"), + RealmPolicySource.text(node, "bindingDigest")), + RealmPolicySource.text(node, "sourceEpoch"), + RealmPolicySource.policiesFromStored(node.get("policies").toString())); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Policy snapshot bytes changed"); + return result; + } + + /** Frozen source only. No terminal association or PUBLISHED claim is represented here. */ + public record Capture(GameDesignPublicationOperation operation, RealmPolicySnapshot snapshot) { + public Capture { + RealmPolicySource.ordered(snapshot.policies()); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen policy snapshot differs from original selected commit"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java new file mode 100644 index 0000000000..9d652b0313 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -0,0 +1,274 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Owner-local typed source; neither these bytes nor a caller's declaration grant authority. */ +public final class RealmPolicySource { + private static final ObjectMapper JSON = new ObjectMapper(); + public static final String SCOPE = "REALM_ENTRY_POLICY_SET"; + public static final int MAX_POLICIES = 128; + + public static final class InvalidPublicationPolicySetException extends IllegalArgumentException { + InvalidPublicationPolicySetException(String message) { + super(message); + } + } + + private RealmPolicySource() {} + + /** + * One owner-authored mutation; the published snapshot continues to retain only effective rows. + */ + public sealed interface Mutation permits Policy, Deletion { + UUID commitId(); + + UUID revisionId(); + + String logicalRevisionId(); + } + + /** Original authored UUID and logical identity survive every inherited snapshot. */ + public record Policy( + UUID commitId, UUID revisionId, String logicalRevisionId, RealmEntryPolicy policy) + implements Mutation { + public Policy { + nonNil(commitId); + nonNil(revisionId); + requireLogicalRevisionId(logicalRevisionId); + policy = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), JSON); + } + } + + /** Explicit deletion carries the exact authored identity and selector in the stored binding. */ + public record Deletion( + UUID commitId, UUID revisionId, String logicalRevisionId, String worldSlug, String realmSlug) + implements Mutation { + public Deletion { + nonNil(commitId); + nonNil(revisionId); + requireLogicalRevisionId(logicalRevisionId); + if (!RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug)) { + throw new IllegalArgumentException("Canonical policy deletion selectors required"); + } + } + } + + /** Closed owner payload, distinct from the policy JSON itself. */ + public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { + var kind = text(tree(input.payload()), "revisionKind"); + if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; + if ("COMMAND_DEFINITION".equals(kind)) return false; + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + + public static Policy revision( + DraftCommitBinding binding, DraftCommitBinding.RevisionPayload input) { + if (input.owner() != DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) { + throw new IllegalArgumentException("Policy revision belongs to Game Design control plane"); + } + JsonNode root = tree(input.payload()); + fields(root, "revisionKind", "logicalRevisionId", "policy"); + if (!RealmEntryPolicy.REVISION_KIND.equals(text(root, "revisionKind"))) { + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + return new Policy( + binding.commitId(), + input.revisionId(), + text(root, "logicalRevisionId"), + RealmEntryPolicy.parse(root.get("policy").toString(), JSON)); + } + + /** Parses one closed owner mutation while preserving the established UPSERT policy parser. */ + public static Mutation mutation( + DraftCommitBinding binding, DraftCommitBinding.RevisionPayload input) { + if (input.owner() != DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) { + throw new IllegalArgumentException("Policy mutation belongs to Game Design control plane"); + } + JsonNode root = tree(input.payload()); + if (!RealmEntryPolicy.REVISION_KIND.equals(text(root, "revisionKind"))) { + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + if (!root.has("operation")) return revision(binding, input); + + fields(root, "revisionKind", "logicalRevisionId", "operation", "worldSlug", "realmSlug"); + if (!"DELETE".equals(text(root, "operation"))) { + throw new IllegalArgumentException("Unsupported realm policy mutation operation"); + } + return new Deletion( + binding.commitId(), + input.revisionId(), + text(root, "logicalRevisionId"), + text(root, "worldSlug"), + text(root, "realmSlug")); + } + + public static List effective(List inherited, List updates) { + Map policies = new LinkedHashMap<>(); + for (Policy policy : draftOrdered(inherited)) policies.put(selector(policy), policy); + var seen = new HashSet(); + for (Mutation mutation : updates) { + String selector = selector(mutation); + if (!seen.add(selector)) { + throw new IllegalArgumentException("A commit repeats a policy selector"); + } + if (mutation instanceof Policy policy) { + policies.put(selector, policy); + } else if (mutation instanceof Deletion deletion) { + Policy existing = policies.get(selector); + if (existing == null) { + throw new IllegalArgumentException("Cannot delete an absent policy selector"); + } + if (!existing.logicalRevisionId().equals(deletion.logicalRevisionId())) { + throw new IllegalArgumentException( + "Policy deletion logical revision identity does not match its selector"); + } + policies.remove(selector); + } + } + return draftOrdered(new ArrayList<>(policies.values())); + } + + public static List ordered(List policies) { + var ordered = draftOrdered(policies); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new InvalidPublicationPolicySetException( + "Complete policy set must contain 1 through 128 policies"); + } + int production = 0; + for (Policy policy : policies) { + if (policy.policy().visible() && policy.policy().publicProduction()) production++; + } + if (production != 1) { + throw new InvalidPublicationPolicySetException( + "Exactly one visible public-production realm required"); + } + return ordered; + } + + /** Draft source may be empty or not yet publication-complete. */ + public static List draftOrdered(List policies) { + if (policies.size() > MAX_POLICIES) + throw new IllegalArgumentException("Draft policy set exceeds 128 policies"); + var realms = new HashSet(); + var revisions = new HashSet(); + for (Policy policy : policies) { + if (!realms.add(policy.policy().realmSlug()) || !revisions.add(policy.revisionId())) { + throw new IllegalArgumentException("Duplicate tenant realm selector or authored revision"); + } + } + return policies.stream() + .sorted( + Comparator.comparing((Policy p) -> p.policy().worldSlug()) + .thenComparing(p -> p.policy().realmSlug())) + .toList(); + } + + static String policiesJson(List policies) { + return canonical( + draftOrdered(policies).stream() + .map( + policy -> + Map.of( + "commitId", + policy.commitId().toString(), + "revisionId", + policy.revisionId().toString(), + "logicalRevisionId", + policy.logicalRevisionId(), + "policy", + tree(policy.policy().canonicalJson()))) + .toList()); + } + + static List policiesFromStored(String bytes) { + JsonNode root = tree(bytes); + if (!root.isArray() || root.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete stored policy array required"); + } + var policies = new ArrayList(); + for (JsonNode node : root) { + fields(node, "commitId", "revisionId", "logicalRevisionId", "policy"); + policies.add( + new Policy( + UUID.fromString(text(node, "commitId")), + UUID.fromString(text(node, "revisionId")), + text(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(node.get("policy").toString(), JSON))); + } + var result = draftOrdered(policies); + if (!policiesJson(result).equals(bytes)) { + throw new IllegalArgumentException("Stored policy snapshot is not canonical"); + } + return result; + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical owner source encoding failed", failure); + } + } + + static JsonNode tree(String value) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(value)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous owner source JSON required", failure); + } + } + + static void fields(JsonNode node, String... fields) { + if (!node.isObject() || node.size() != fields.length) { + throw new IllegalArgumentException("Closed owner source fields required"); + } + for (String field : fields) + if (!node.has(field)) throw new IllegalArgumentException("Missing " + field); + } + + static String text(JsonNode node, String field) { + if (!node.path(field).isTextual()) + throw new IllegalArgumentException("Text required: " + field); + return node.get(field).asText(); + } + + private static String selector(Policy policy) { + return policy.policy().worldSlug() + "/" + policy.policy().realmSlug(); + } + + private static String selector(Mutation mutation) { + if (mutation instanceof Policy policy) return selector(policy); + Deletion deletion = (Deletion) mutation; + return deletion.worldSlug() + "/" + deletion.realmSlug(); + } + + private static void requireLogicalRevisionId(String value) { + if (value == null + || value.isBlank() + || value.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + } + + private static void nonNil(UUID value) { + if (value == null || new UUID(0, 0).equals(value)) + throw new IllegalArgumentException("Non-nil authored UUID required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java new file mode 100644 index 0000000000..a7ffd4492d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -0,0 +1,615 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage, with no runtime registration or creator authorization. Missing actual + * source baseline denies. Empty genesis can only be enrolled in the actual Version insert + * transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner storage collaborator.") +public final class RealmPolicySourceRepository { + private final DSLContext dsl; + + public RealmPolicySourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Parent invokes only from the new Version insert branch, in that same owner transaction. */ + public RealmPolicyGenesis recordFreshGenesis(TargetProof target) { + requireWrite(); + lockAuthority(target); + var prior = readGenesis(target); + if (prior.isPresent()) return prior.orElseThrow(); + requireDraftAndUnfrozen(target); + var witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); + var receipt = new RealmPolicyGenesis(target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_realm_policy_genesis " + + "(canonical_tenant_id, canonical_version_id, receipt_id, version_id, creation_transaction_id, receipt_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId(), + target.gameDesignVersionRowId(), + receipt.creationTransactionId(), + receipt.canonicalJson()); + dsl.execute( + "INSERT INTO game_design_realm_policy_source " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, genesis_receipt_id) VALUES (?, ?, '0', NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId()); + return readGenesis(target).orElseThrow(); + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var receipt = + new RealmPolicyGenesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (!receipt.canonicalJson().equals(row.get("receipt_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) { + throw new IllegalStateException("POLICY_GENESIS_TARGET_CONFLICT"); + } + return Optional.of(receipt); + } + + /** Caller must already own the authorized coordinator application slot. */ + public RealmPolicyApplication apply(DraftCommitBinding binding) { + requirePolicyOnly(binding); + var result = applyMutation(binding); + recordCompleteOwnerOutcome(binding, result.ownerOutcome()); + return result; + } + + /** + * Stages only policy mutation evidence; parent records one complete owner outcome before commit. + */ + public RealmPolicyApplication applyMutation(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + var prior = application(binding); + if (prior.isPresent()) { + var result = prior.orElseThrow(); + return result; + } + requireDraftAndUnfrozen(binding.target()); + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_ALREADY_RESERVED"); + } + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var slot = + coordinator + .readApplicationSlot(binding.target()) + .orElseThrow(() -> new IllegalStateException("POLICY_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("POLICY_APPLICATION_SLOT_CHANGED"); + } + var state = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && state.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("POLICY_OWNER_APPLICATION_NOT_STARTED"); + } + var source = source(binding.target()); + UUID inherited = source.get("visible_commit_id", UUID.class); + String epoch = source.get("source_epoch", String.class); + var genesis = + source.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(); + if (genesis != null + && !genesis.receiptId().equals(source.get("genesis_receipt_id", UUID.class))) { + throw new IllegalStateException("POLICY_GENESIS_SOURCE_CONFLICT"); + } + List inheritedPolicies; + if (inherited == null) { + if (genesis == null + || !"0".equals(epoch) + || new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .isPresent()) { + throw new IllegalStateException("POLICY_SOURCE_GENESIS_NOT_CURRENT"); + } + inheritedPolicies = List.of(); + } else { + requireCurrentFence(binding.target(), inherited); + var previous = readSnapshot(binding.target(), inherited).orElseThrow(); + if (!previous.sourceEpoch().equals(epoch)) + throw new IllegalStateException("POLICY_SOURCE_UNSYNCHRONIZED"); + inheritedPolicies = previous.policies(); + } + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(u -> RealmPolicySource.SCOPE.equals(u.aggregateType())) + .toList(); + if (units.size() != 1 + || !RealmPolicySource.SCOPE.equals(units.getFirst().aggregateType()) + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !RealmPolicySource.SCOPE.equals(units.getFirst().scopeType()) + || !"effective".equals(units.getFirst().scopeId()) + || !epoch.equals(units.getFirst().expectedEpoch())) { + throw new IllegalArgumentException( + "Complete policy-set containing scope and exact epoch required"); + } + var updates = + binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(r -> RealmPolicySource.mutation(binding, r)) + .toList(); + if (updates.isEmpty()) + throw new IllegalArgumentException("Typed authored policy revisions required"); + for (RealmPolicySource.Mutation update : updates) { + String revisionBinding = + RealmPolicySource.canonical( + List.of(java.util.Map.of("revisionId", update.revisionId().toString()))); + if (dsl.fetchExists( + dsl.selectOne() + .from("game_design_realm_policy_application a") + .join("game_design_draft_commit c") + .on( + "c.canonical_tenant_id = a.canonical_tenant_id " + + "AND c.canonical_version_id = a.canonical_version_id " + + "AND c.request_id = a.request_id AND c.commit_id = a.commit_id") + .where( + "a.canonical_tenant_id = ? AND a.canonical_version_id = ? " + + "AND (c.binding_json::jsonb -> 'revisions') @> ?::jsonb", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + revisionBinding))) { + throw new IllegalArgumentException("Authored policy revision identity cannot be reused"); + } + if (inheritedPolicies.stream().anyMatch(p -> p.revisionId().equals(update.revisionId()))) { + throw new IllegalArgumentException("Authored baseline revision identity cannot be reused"); + } + } + var snapshot = + new RealmPolicySnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + RealmPolicySource.effective(inheritedPolicies, updates)); + var result = new RealmPolicyApplication(genesis, inherited, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_realm_policy_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, genesis_receipt_id, expected_epoch, snapshot_json, result_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + inherited, + genesis == null ? null : genesis.receiptId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + int advanced = + dsl.execute( + "UPDATE game_design_realm_policy_source SET source_epoch = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited); + if (advanced != 1) throw new IllegalStateException("POLICY_SOURCE_EPOCH_CONFLICT"); + var retained = application(binding).orElseThrow(); + return retained; + } + + /** Parent supplies actual sibling evidence and every exact owned epoch to one shared result. */ + public void recordCombinedOwnerOutcome( + DraftCommitBinding binding, + byte[] siblingEvidence, + List completeEpochs) { + requireWrite(); + lockAuthority(binding.target()); + var result = application(binding).orElseThrow(); + recordCompleteOwnerOutcome( + binding, result.combinedOwnerOutcome(siblingEvidence, completeEpochs)); + } + + private void recordCompleteOwnerOutcome( + DraftCommitBinding binding, DraftCommitCoordinatorRepository.OwnerOutcome outcome) { + requireWrite(); + var row = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) throw new IllegalStateException("POLICY_OWNER_APPLICATION_UNAVAILABLE"); + byte[] previous = row.get(0, byte[].class); + if (previous != null && !Arrays.equals(previous, outcome.resultBytes())) { + throw new IllegalArgumentException("POLICY_COMPLETE_OWNER_RESULT_CHANGED"); + } + new DraftCommitCoordinatorRepository(dsl).recordOwnerOutcome(binding, outcome); + if (previous == null) + dsl.execute( + "UPDATE game_design_realm_policy_application SET owner_result_bytes = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + outcome.resultBytes(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + requireCoordinatorResult(application(binding).orElseThrow()); + } + + private static void requirePolicyOnly(DraftCommitBinding binding) { + if (binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .anyMatch(r -> !RealmPolicySource.isPolicyRevision(r)) + || binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .anyMatch(u -> !RealmPolicySource.SCOPE.equals(u.aggregateType()))) { + throw new IllegalArgumentException( + "Mixed Game Design commit requires one combined owner result"); + } + } + + /** + * Invoke in the transaction that advances the coordinator fence, before releasing its slot. A + * disjoint synchronized commit inherits the last complete snapshot; staged owner rows never + * become visible. Absence of a baseline is a denial, including for retained content. + */ + public RealmPolicySnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + requireCurrentFence(binding.target(), binding.commitId()); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("POLICY_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + requireDraftAndUnfrozen(binding.target()); + var source = source(binding.target()); + UUID previousCommit = source.get("visible_commit_id", UUID.class); + var previous = + previousCommit == null + ? null + : readSnapshot(binding.target(), previousCommit).orElseThrow(); + if (previous == null + && (source.get("genesis_receipt_id", UUID.class) == null + || readGenesis(binding.target()).isEmpty())) { + throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + } + var applied = application(binding); + RealmPolicySnapshot snapshot; + if (binding.revisions().stream() + .anyMatch( + r -> + r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(r))) { + var result = + applied.orElseThrow(() -> new IllegalStateException("POLICY_OWNER_RESULT_UNAVAILABLE")); + requireCoordinatorResult(result); + if (!Objects.equals(result.inheritedCommitId(), previousCommit)) { + throw new IllegalStateException("POLICY_SNAPSHOT_PREDECESSOR_CHANGED"); + } + snapshot = result.snapshot(); + } else { + snapshot = + new RealmPolicySnapshot( + binding, + previous == null ? "0" : previous.sourceEpoch(), + previous == null ? List.of() : previous.policies()); + } + if (!snapshot.sourceEpoch().equals(source.get("source_epoch", String.class))) { + throw new IllegalStateException("PARTIAL_POLICY_OWNER_WRITE_NOT_VISIBLE"); + } + dsl.execute( + "INSERT INTO game_design_realm_policy_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, snapshot_json) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + previousCommit, + snapshot.canonicalJson()); + dsl.execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public RealmPolicySnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + var selection = operation.account().input().selection(); + var target = selection.target(); + lockAuthority(target); + var existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireDraftAndUnfrozen(target); + var row = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null + || !selection.canonicalJson().equals(row.get("selection_json", String.class)) + || !selection.digest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_UNAVAILABLE"); + } + // The Version lock serializes this check with the owner finalizer. Do not acquire its earlier + // game/attempt locks after the Version lock and invert the existing publication lock order. + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_SEALED"); + var versionEpoch = + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + Long persistedEpoch = versionEpoch == null ? null : versionEpoch.get(0, Long.class); + if (persistedEpoch == null || persistedEpoch <= 0) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_EPOCH_UNAVAILABLE"); + } + if (!selection.intent().expectedVersionStateEpoch().equals(Long.toString(persistedEpoch))) { + throw new IllegalStateException("POLICY_PUBLICATION_DRAFT_EPOCH_CHANGED"); + } + requireCurrentFence(target, selection.selectedCommit().commitId()); + var source = source(target); + var snapshot = readSnapshot(target, selection.selectedCommit().commitId()).orElseThrow(); + if (!source.get("visible_commit_id", UUID.class).equals(snapshot.binding().commitId()) + || !source.get("source_epoch", String.class).equals(snapshot.sourceEpoch())) { + throw new IllegalStateException("POLICY_FROZEN_SOURCE_NOT_SYNCHRONIZED"); + } + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_realm_policy_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class))) { + throw new IllegalArgumentException("POLICY_FREEZE_OPERATION_CONFLICT"); + } + var snapshot = readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow(); + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json FROM game_design_realm_policy_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId)) { + throw new IllegalStateException("POLICY_SNAPSHOT_OWNER_CONFLICT"); + } + exactCommit(snapshot.binding()); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId, + snapshot.binding().requestId()); + if (fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("POLICY_SNAPSHOT_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + for (var policy : snapshot.policies()) { + var authored = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + policy.commitId()); + if (authored == null) + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_UNAVAILABLE"); + var binding = + DraftCommitBinding.fromStored( + authored.get("binding_json", String.class), + authored.get("input_digest", String.class)); + var revision = + binding.revisions().stream() + .filter(r -> r.revisionId().equals(policy.revisionId())) + .findFirst() + .orElseThrow(); + if (!binding.target().equals(target) + || !RealmPolicySource.revision(binding, revision).equals(policy)) { + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_CHANGED"); + } + } + return Optional.of(snapshot); + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new RealmPolicyApplication( + row.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(), + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!result.snapshot().binding().equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_APPLICATION_EXACT_BINDING_CONFLICT"); + } + return Optional.of(result); + } + + private void requireCoordinatorResult(RealmPolicyApplication result) { + var binding = result.snapshot().binding(); + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + var stored = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (state == null + || state.outcome().isEmpty() + || stored == null + || !Arrays.equals(state.outcome().orElseThrow().resultBytes(), stored.get(0, byte[].class)) + || !state + .outcome() + .orElseThrow() + .appliedEpochs() + .contains(result.ownerOutcome().appliedEpochs().getFirst())) { + throw new IllegalStateException("POLICY_COORDINATOR_RESULT_CONFLICT"); + } + } + + private Record source(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + return row; + } + + private void requireCurrentFence(TargetProof target, UUID commitId) { + var current = + new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).orElseThrow(); + if (!current.commitId().equals(commitId)) + throw new IllegalStateException("POLICY_VISIBLE_FENCE_CHANGED"); + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(); + if (!retained.binding().equals(binding)) + throw new IllegalArgumentException("POLICY_COMMIT_BINDING_CONFLICT"); + } + + private void requireDraftAndUnfrozen(TargetProof target) { + var version = + dsl.fetchOne( + "SELECT version_state, is_script_only, script_patch_version, base_version_id FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + if (version == null + || !"DRAFT".equals(version.get("version_state", String.class)) + || !Boolean.FALSE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void lockAuthority(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT v.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.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) + throw new IllegalStateException("POLICY_CANONICAL_OWNER_AUTHORITY_UNAVAILABLE"); + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Policy writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java new file mode 100644 index 0000000000..30f1009f94 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Independent immutable readback boundary. Writes deliberately remain caller-transaction owned so + * the authenticated coordinator can compose application, visibility and publication atomically. No + * transport registration, retained-baseline initializer, terminal association or activation exists + * here. + */ +public final class RealmPolicySourceService { + private final RealmPolicySourceRepository repository; + private final TransactionTemplate read; + + public RealmPolicySourceService( + RealmPolicySourceRepository repository, PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + public Optional readSnapshot( + DraftCommitBinding.TargetProof target, UUID commitId) { + requireIndependent(); + return read.execute(status -> repository.readSnapshot(target, commitId)); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + requireIndependent(); + return read.execute(status -> repository.readCapture(operation)); + } + + public Optional readGenesis(DraftCommitBinding.TargetProof target) { + requireIndependent(); + return read.execute(status -> repository.readGenesis(target)); + } + + private static void requireIndependent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Independent immutable policy readback required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index ea1b7062d4..e381634a72 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -120,7 +120,27 @@ public Game findByTenantIdForUpdate(String tenantId) { .fetchOne(this::toEntity); } - /** Resolves one exact owner key and validates persisted provenance against its game row. */ + /** Reads one persisted tenant UUID and validates its provenance against the actual owner row. */ + public Optional findRuntimeTenantIdentityByCanonicalTenantId( + UUID canonicalTenantId) { + if (canonicalTenantId == null) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + return dsl.select( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .fetchOptional(this::toRuntimeTenantIdentity); + } + + /** + * Resolves the exact existing owner tenant key to its persisted canonical UUID and provenance. + */ public Optional findRuntimeTenantIdentityByTenantKey(String tenantKey) { if (tenantKey == null || tenantKey.isBlank()) { throw new IllegalArgumentException("Exact Game Design tenant key is required"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 3cd508c007..4e285801e9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -8,7 +8,8 @@ import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; -import org.jooq.Condition; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -29,6 +30,7 @@ public class PublishAttemptRepository { private static final Field PUBLISH_TYPE = DSL.field(DSL.name("publish_type"), String.class); private static final Field STATUS = DSL.field(DSL.name("status"), String.class); + private static final Field REVISION = DSL.field(DSL.name("revision"), Long.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); @@ -73,40 +75,50 @@ public Optional findByPublishWorkflowIdForUpdate(String workflow .fetchOne(this::toEntity)); } - /** - * Installs a compatibility digest only once, and only on the exact legacy full-version row whose - * identity was validated by the caller. - * - *

The conditional update makes concurrent retries idempotent: the first writer installs the - * digest and later writers can only read the already-installed value. It deliberately does not - * derive or replace a digest for any other attempt shape. - */ - public Optional backfillFullVersionRequestDigestIfAbsent( - Long attemptId, - String tenantId, - String publishWorkflowId, - Long versionId, - int versionNumber, - String requestDigest) { - if (attemptId == null || requestDigest == null || requestDigest.isBlank()) { - return Optional.empty(); + public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence + requirePublicationPending(PublishAttempt attempt) { + return new GameDesignPublicationOperationRepository(dsl) + .requirePending( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest()) + .world(); + } + + public void sealPublication(PublishAttempt attempt, boolean published) { + new GameDesignPublicationOperationRepository(dsl) + .seal( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest(), + published); + if (published) { + new RealmPolicyPublicationRepository(dsl) + .retainSealedPublished(attempt.getPublishWorkflowId()); + } + } + + public void requirePublishedOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "PUBLISHED"); + } + + public void requireNoPublicationOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "NO_PUBLICATION"); + } + + private void requireTerminalOperation(PublishAttempt attempt, String outcome) { + var result = + new GameDesignPublicationOperationRepository(dsl) + .read(attempt.getPublishWorkflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!outcome.equals(result.outcome()) + || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) + || result.operation().versionId() != attempt.getVersionId() + || !result.operation().tenantKey().equals(attempt.getTenantId())) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); } - Condition fullVersionAttemptIdentity = - ID.eq(attemptId) - .and(TENANT_ID.eq(tenantId)) - .and(PUBLISH_WORKFLOW_ID.eq(publishWorkflowId)) - .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) - .and(VERSION_ID.eq(versionId)) - .and(VERSION_NUMBER.eq(versionNumber)); - dsl.update(PUBLISH_ATTEMPT_TABLE) - .set(REQUEST_DIGEST, requestDigest) - .where(fullVersionAttemptIdentity.and(REQUEST_DIGEST.isNull())) - .execute(); - return Optional.ofNullable( - dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) - .where(fullVersionAttemptIdentity) - .limit(1) - .fetchOne(this::toEntity)); } public PublishAttempt save(PublishAttempt attempt) { @@ -128,26 +140,50 @@ public PublishAttempt save(PublishAttempt attempt) { .set(FAILURE_MESSAGE, attempt.getFailureMessage()) .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .returning() + .returning( + ID, + TENANT_ID, + PUBLISH_WORKFLOW_ID, + PUBLISH_TYPE, + STATUS, + REVISION, + VERSION_ID, + VERSION_NUMBER, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + REQUEST_DIGEST, + FAILURE_CODE, + FAILURE_MESSAGE, + CREATED_AT, + COMPLETED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Publish attempt insert did not return its persisted row"); + } return toEntity(record); } - dsl.update(PUBLISH_ATTEMPT_TABLE) - .set(TENANT_ID, attempt.getTenantId()) - .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) - .set(PUBLISH_TYPE, attempt.getPublishType().name()) - .set(STATUS, attempt.getStatus().name()) - .set(VERSION_ID, attempt.getVersionId()) - .set(VERSION_NUMBER, attempt.getVersionNumber()) - .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) - .set(BASE_VERSION_ID, attempt.getBaseVersionId()) - .set(REQUEST_DIGEST, attempt.getRequestDigest()) - .set(FAILURE_CODE, attempt.getFailureCode()) - .set(FAILURE_MESSAGE, attempt.getFailureMessage()) - .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) - .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .where(ID.eq(attempt.getId())) - .execute(); + int changed = + dsl.update(PUBLISH_ATTEMPT_TABLE) + .set(TENANT_ID, attempt.getTenantId()) + .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) + .set(PUBLISH_TYPE, attempt.getPublishType().name()) + .set(STATUS, attempt.getStatus().name()) + .set(REVISION, Math.addExact(attempt.getRevision(), 1L)) + .set(VERSION_ID, attempt.getVersionId()) + .set(VERSION_NUMBER, attempt.getVersionNumber()) + .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) + .set(BASE_VERSION_ID, attempt.getBaseVersionId()) + .set(REQUEST_DIGEST, attempt.getRequestDigest()) + .set(FAILURE_CODE, attempt.getFailureCode()) + .set(FAILURE_MESSAGE, attempt.getFailureMessage()) + .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) + .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) + .where( + ID.eq(attempt.getId()) + .and(REVISION.eq(attempt.getRevision())) + .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) + .execute(); + if (changed != 1) throw new IllegalStateException("PUBLISH_ATTEMPT_CAS_CONFLICT"); return findByPublishWorkflowId(attempt.getPublishWorkflowId()).orElseThrow(); } @@ -157,6 +193,7 @@ private PublishAttempt toEntity(Record record) { } PublishAttempt attempt = new PublishAttempt(); attempt.setId(record.get(ID)); + attempt.setRevision(record.get(REVISION)); attempt.setTenantId(record.get(TENANT_ID)); attempt.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); String publishType = record.get(PUBLISH_TYPE); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index e79d27c9fe..f1bc1c0733 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -4,11 +4,17 @@ import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -107,6 +113,54 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + /** + * Reads the exact full-version command snapshot frozen for the retained publication operation. + * The requested Version tuple, operation selection, World evidence, and both source captures are + * checked before a bundle producer can persist command bytes. + */ + public List requireSelectedCommandDefinitions( + String tenantId, + Long versionId, + String publishWorkflowId, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(publishWorkflowId, "publishWorkflowId"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + + GameDesignPublicationOperation operation = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .map(GameDesignPublicationOperationRepository.Readback::operation) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_OPERATION_UNAVAILABLE")); + var selection = operation.account().input().selection(); + var target = selection.target(); + if (!tenantId.equals(operation.tenantKey()) + || !versionId.equals(operation.versionId()) + || !publishWorkflowId.equals(operation.workflowId()) + || !tenantId.equals(target.gameDesignVersionTenantKey()) + || !versionId.equals(target.gameDesignVersionRowId()) + || !Arrays.equals(operation.world().canonicalBytes(), worldEvidence.canonicalBytes()) + || !target.canonicalTenantId().equals(worldEvidence.request().canonicalTenantId()) + || !target.canonicalVersionId().equals(worldEvidence.request().canonicalVersionId()) + || !publishWorkflowId.equals(worldEvidence.request().publishWorkflowId())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CONFLICT"); + } + + GameDesignSourceRepository.Capture capture = + new GameDesignSourceRepository(dsl) + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + if (!Arrays.equals( + capture.command().operation().canonicalBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("SELECTED_COMMAND_CAPTURE_OPERATION_CONFLICT"); + } + return capture.command().snapshot().definitions().stream() + .map(CommandSource.Definition::definitionJson) + .toList(); + } + public PublishedReleaseBundle save(PublishedReleaseBundle bundle) { Objects.requireNonNull(bundle, "bundle"); if (bundle.getId() != null) { @@ -133,6 +187,21 @@ private PublishedReleaseBundle insertNewBundle( "Unsupported published release bundle attestation schema " + bundle.getAttestationSchemaVersion()); } + if ("v2".equals(bundle.getAttestationSchemaVersion())) { + PublishedReleaseBundle existing = + tx.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) + .fetchOne(this::toEntity); + if (existing != null) { + try { + verifyPersistedSource(existing, bundle, source, existing.getPublishedReleaseBundleRef()); + } catch (IllegalStateException conflict) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input", conflict); + } + return existing; + } + } String publishedReleaseBundleRef = UUID.randomUUID().toString(); Long generatedId = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index edcd68557b..c74a4f5da5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -7,14 +7,20 @@ 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.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; 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.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -219,7 +225,20 @@ public long count() { return dsl.fetchCount(VERSION_TABLE); } + @Transactional(isolation = Isolation.READ_COMMITTED) public Version save(Version version) { + if (version.getId() == null + && version.getVersionState() == VersionLifecycleState.DRAFT + && !version.isScriptOnly() + && version.getBaseVersionId() == null + && version.getScriptPatchVersion() == null + && (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()))) { + throw new IllegalStateException( + "New full Draft creation requires one writable READ_COMMITTED source transaction"); + } LocalDateTime createdAt = version.getCreatedAt() == null ? LocalDateTime.now() : version.getCreatedAt(); LocalDateTime updatedAt = @@ -266,6 +285,21 @@ public Version save(Version version) { Version inserted = toEntity(record); Version persisted = findById(inserted.getId()).orElseThrow(); requireIssuedIdentityReadback(persisted, inserted.getTenantId(), canonicalVersionId, source); + if (persisted.getVersionState() == VersionLifecycleState.DRAFT + && !persisted.isScriptOnly() + && persisted.getBaseVersionId() == null + && persisted.getScriptPatchVersion() == null) { + new GameDesignSourceRepository(dsl) + .enrollFreshDraft( + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind())); + } return persisted; } dsl.update(VERSION_TABLE) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java index 4265e6884c..2b09e9d3e1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java @@ -6,6 +6,17 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; public interface PublishedReleaseBundleService { + /** + * Requires evidence already obtained over the authenticated World client before this transaction. + */ + PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + java.util.List participantDigests, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldEvidence); + PublishedReleaseBundleDto createFullVersionBundle( VersionDto version, String publishWorkflowId, 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..a283225048 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,7 +12,12 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; public interface VersionService { - VersionDto publishVersion(String tenantId, String notes, String publishRequestId) + VersionDto publishVersion(PublishIntent intent) throws Exception; + + /** + * Replays retained terminal evidence for a pre-selection request; it cannot start publication. + */ + VersionDto replayLegacyFullVersion(String tenantId, String notes, String publishRequestId) throws Exception; VersionDto publishScriptPatchVersion( 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 7ac74b4e2d..952e81d7de 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 @@ -18,6 +18,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,9 +227,40 @@ public void publishVersion( if (request.getPublishRequestId().isBlank()) { throw new IllegalArgumentException("publish_request_id is required"); } - VersionDto version = - versionService.publishVersion( - request.getTenantId(), request.getNotes(), request.getPublishRequestId()); + boolean noSelection = + request.getVersionId().isBlank() + && request.getExpectedVersionStateEpoch().isBlank() + && request.getSelectedCommitRequestId().isBlank() + && request.getSelectedCommitId().isBlank() + && request.getSelectedCommitDigest().isBlank(); + boolean completeSelection = + !request.getVersionId().isBlank() + && !request.getExpectedVersionStateEpoch().isBlank() + && !request.getSelectedCommitRequestId().isBlank() + && !request.getSelectedCommitId().isBlank() + && !request.getSelectedCommitDigest().isBlank(); + VersionDto version; + if (noSelection) { + version = + versionService.replayLegacyFullVersion( + request.getTenantId(), request.getNotes(), request.getPublishRequestId()); + } else if (completeSelection) { + version = + versionService.publishVersion( + 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())); + } else { + throw new IllegalArgumentException( + "all selected version, epoch, commit, and digest fields are required together"); + } builder.setVersionId(version.id()); } catch (AdminAuthorizationException ex) { builder.setError( @@ -2268,6 +2300,11 @@ private String publishAttemptErrorCode(RuntimeException failure) { "PUBLISH_ATTEMPT_INCONSISTENT", "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED", "PUBLISH_ATTEMPT_SCOPE_MISMATCH", + "FULL_VERSION_PUBLICATION_UNAVAILABLE", + "PUBLICATION_AUTHORIZATION_UNAVAILABLE", + "PUBLISH_OWNER_CARRIER_UNAVAILABLE", + "PUBLISH_SELECTION_REQUIRED", + "SELECTED_SOURCE_CAPTURE_UNAVAILABLE", "PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT" -> candidate; default -> null; @@ -2278,6 +2315,14 @@ private void requireLaunchAttestationReadAccess() { requireCandidatePeerThenDeny(Set.of("game-session-service", "world-management-service")); } + 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 requirePublishedReleaseBundleReadAccess() { requireCandidatePeerThenDeny( Set.of("game-session-service", "world-management-service", "automation-scripting-service")); 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 84185929fa..f4d6df9c29 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/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index 3fdd6161c5..f40b92aa71 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -1,9 +1,13 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.Arrays; import java.util.List; import java.util.Objects; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; final class PublishedReleaseBundleContract { @@ -88,6 +92,37 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { } } + static void requireExactSelectorRetry( + PublishedReleaseBundleDto stored, + VersionDto version, + String workflow, + ExportedAssetManifest manifest, + String generationRevision, + List participants, + WorldPublishedStartLocationEvidence evidence) { + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); + } + requireSelectorBinding(stored); + if (stored.versionNumber() != version.versionNumber() + || version.scriptOnly() + || version.scriptPatchVersion() != null + || !Objects.equals(stored.publishWorkflowId(), workflow) + || !Objects.equals(stored.manifestHash(), manifest.manifestHash()) + || !Objects.equals(stored.manifestSchemaVersion(), manifest.manifestSchemaVersion()) + || !Objects.equals(stored.artifactDigests(), manifest.artifactDigests()) + || !stored.requiredManifestAssetKeys().equals(manifest.requiredManifestAssetKeys()) + || !Objects.equals(stored.generationConfigRevision(), generationRevision) + || !stored.participantDigests().equals(participants) + || !Arrays.equals( + stored.worldPublishedStartLocationEvidence().canonicalBytes(), + evidence.canonicalBytes())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input"); + } + } + static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -97,6 +132,17 @@ static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { } } + /** + * Publication reconciliation only; does not widen launch or repair authorization/schema support. + */ + static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForRead(bundle); + } + static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalArgumentException( @@ -106,6 +152,9 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + /** + * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. + */ static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { requireSelectorBinding(bundle); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 44f850227d..f0551d3cc8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -2,15 +2,22 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; @@ -25,11 +32,16 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundleService { private final PublishedReleaseBundleRepository repository; + private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( - PublishedReleaseBundleRepository repository, ObjectMapper objectMapper) { + PublishedReleaseBundleRepository repository, + VersionRepository versionRepository, + ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); + this.versionRepository = + Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } @@ -45,6 +57,105 @@ public PublishedReleaseBundleDto createFullVersionBundle( "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); } + @Override + @Transactional + public PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); + Objects.requireNonNull(version, "version must not be null"); + Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); + Objects.requireNonNull(participantDigests, "participantDigests must not be null"); + Optional existing = + repository.findByTenantIdAndVersionId(version.tenantId(), version.id()); + if (existing.isPresent()) { + PublishedReleaseBundleDto stored = toDto(existing.orElseThrow()); + PublishedReleaseBundleContract.requireExactSelectorRetry( + stored, + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + List originalCommandDefinitions = + repository.requireSelectedCommandDefinitions( + stored.tenantId(), + stored.versionId(), + stored.publishWorkflowId(), + stored.worldPublishedStartLocationEvidence()); + if (!stored.commandDefinitions().equals(originalCommandDefinitions)) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: stored command definitions differ from the original source capture"); + } + return stored; + } + var identitySource = + versionRepository + .findByTenantIdAndId(version.tenantId(), version.id()) + .orElseThrow( + () -> + new IllegalStateException( + "published release canonical identity source missing")); + UUID canonicalTenantId = identitySource.getCanonicalTenantId(); + UUID canonicalVersionId = identitySource.getCanonicalVersionId(); + if (!version.id().equals(identitySource.getId()) + || !version.tenantId().equals(identitySource.getTenantId()) + || !isCanonicalNonNilUuid(canonicalTenantId) + || !isCanonicalNonNilUuid(canonicalVersionId)) { + throw new IllegalStateException("published release canonical identity source is invalid"); + } + PublishedReleaseBundle entity = new PublishedReleaseBundle(); + entity.setTenantId(version.tenantId()); + entity.setVersionId(version.id()); + entity.setCanonicalTenantId(canonicalTenantId); + entity.setCanonicalVersionId(canonicalVersionId); + entity.setVersionNumber(version.versionNumber()); + entity.setAttestationSchemaVersion( + PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + entity.setWorldPublishedStartLocationEvidenceJson( + new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); + entity.setPublishWorkflowId(publishWorkflowId); + entity.setManifestHash(exportedManifest.manifestHash()); + entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); + entity.setArtifactDigestsJson( + objectMapper.writeValueAsString(exportedManifest.artifactDigests())); + entity.setGenerationConfigRevision(generationConfigRevision); + entity.setRequiredManifestAssetKeysJson( + serializeKeys(exportedManifest.requiredManifestAssetKeys())); + entity.setParticipantDigestsJson(serializeParticipantDigests(participantDigests)); + List commandDefinitions = + repository.requireSelectedCommandDefinitions( + version.tenantId(), version.id(), publishWorkflowId, worldEvidence); + validateDistinctCommandDefinitions(commandDefinitions); + entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); + entity.setScriptOnly(version.scriptOnly()); + entity.setScriptPatchVersion(version.scriptPatchVersion()); + toDto(entity); + return toDto(repository.save(entity)); + } + @Override @Transactional(readOnly = true) public PublishedReleaseBundleDto getPublishedReleaseBundle(String tenantId, long versionId) { @@ -131,4 +242,55 @@ private List deserializeParticipantDigests(String j .getTypeFactory() .constructCollectionType(List.class, PublishParticipantDigestDto.class)); } + + private boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); + } + + private String serializeKeys(List keys) { + return objectMapper.writeValueAsString(keys == null ? List.of() : List.copyOf(keys)); + } + + private String serializeParticipantDigests(List participantDigests) { + return objectMapper.writeValueAsString( + participantDigests == null ? List.of() : List.copyOf(participantDigests)); + } + + private String serializeCommandDefinitions(List commandDefinitions) { + return objectMapper.writeValueAsString( + commandDefinitions == null ? List.of() : commandDefinitions); + } + + private void validateDistinctCommandDefinitions(List commandDefinitions) { + Map tokenOwners = new HashMap<>(); + Set commandIds = new HashSet<>(); + for (String commandDefinition : commandDefinitions) { + var definition = objectMapper.readTree(commandDefinition); + CommandEffectDeclarationValidator.validateAll(definition.path("effects")); + String commandId = normalizeCommandToken(definition.path("commandId").asText()); + if (!commandIds.add(commandId)) { + throw new IllegalStateException("duplicate published commandDefinition id " + commandId); + } + ensureSingleTokenOwner(tokenOwners, commandId, commandId); + for (var alias : definition.path("aliases")) { + String normalizedAlias = normalizeCommandToken(alias.asText()); + ensureSingleTokenOwner(tokenOwners, normalizedAlias, commandId); + } + } + } + + private void ensureSingleTokenOwner( + Map tokenOwners, String token, String commandId) { + String existingOwner = tokenOwners.putIfAbsent(token, commandId); + if (existingOwner != null && !existingOwner.equals(commandId)) { + throw new IllegalStateException("ambiguous published commandDefinition token " + token); + } + } + + private String normalizeCommandToken(String value) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("published commandDefinition token must not be blank"); + } + return value.trim().toLowerCase(Locale.ROOT); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java index b95e655872..aa913519ca 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -128,8 +128,9 @@ private FrozenAssetExportCandidate recordInOwnerTransaction( .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); var attempt = attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); - // Candidate recording is not publication authority. If an attempt exists, enforce its exact - // tenant, Version, and pending status before admitting candidate evidence. + // Standalone private candidate recording is not publication authority. If an actual selected + // attempt exists, its immutable operation must still be open before any new candidate + // admission. if (attempt.isPresent()) { var current = attempt.get(); if (!Objects.equals(current.getTenantId(), tenantId) @@ -137,6 +138,7 @@ private FrozenAssetExportCandidate recordInOwnerTransaction( || current.getStatus() != PublishAttemptStatus.PENDING) { throw new IllegalStateException(CANDIDATE_CONFLICT); } + if (current.getRequestDigest() != null) attemptRepository.requirePublicationPending(current); } Version version = versionRepository 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 7e4858e986..b75f335bc1 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 @@ -2,20 +2,25 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.LocalDateTime; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; 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; @@ -55,6 +60,7 @@ public class VersionPublishCommandServiceImpl { private final VersionAssetArtifactService versionAssetArtifactService; private final PublishedReleaseBundleService publishedReleaseBundleService; private final RecordedParticipantDigestService recordedParticipantDigestService; + private final AuthoredDraftPublishSelectionRepository authoredSelections; public VersionPublishCommandServiceImpl( VersionRepository versionRepository, @@ -67,7 +73,8 @@ public VersionPublishCommandServiceImpl( ControlPlaneDigestService controlPlaneDigestService, VersionAssetArtifactService versionAssetArtifactService, PublishedReleaseBundleService publishedReleaseBundleService, - RecordedParticipantDigestService recordedParticipantDigestService) { + RecordedParticipantDigestService recordedParticipantDigestService, + AuthoredDraftPublishSelectionRepository authoredSelections) { this.versionRepository = versionRepository; this.gameRepository = gameRepository; this.publishAttemptRepository = publishAttemptRepository; @@ -79,6 +86,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( @@ -95,6 +131,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(), @@ -121,16 +160,17 @@ PublishWorkflowSnapshot reconcileFullVersionPublishMechanics(PublishWorkflowRequ PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { + requireSelectedIntent(request); + requireCanonicalOwnerPublicationCarrier(request); attempt = reserveDraftAttempt(request); } - if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - return replayTerminalAttempt(request, attempt); - } - if (attempt.getStatus() == PublishAttemptStatus.FAILED) { + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED + || attempt.getStatus() == PublishAttemptStatus.FAILED) { return replayTerminalAttempt(request, attempt); } - attempt = backfillLegacyFullVersionRequestDigest(request, attempt); + requireSelectedIntent(request); validateFullVersionAttempt(attempt, request); + requireCanonicalOwnerPublicationCarrier(request); Version version = requireAttemptVersion(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); @@ -145,6 +185,32 @@ PublishWorkflowSnapshot reconcileFullVersionPublishMechanics(PublishWorkflowRequ throw pendingReconciliation( "pending full-version attempt does not reference a draft version"); } + requireSelectedDraftEpoch(request, version); + return reconcileSelectedPublicationMechanics(request); + } + + private 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; @@ -162,6 +228,7 @@ PublishWorkflowSnapshot reconcileFullVersionPublishMechanics(PublishWorkflowRequ return failDefinitively(request, attempt, version, null, ex); } try { + assertSelectedCommit(request, participantDigests); publishGateService.assertGatePassed(dto, participantDigests); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { @@ -177,38 +244,33 @@ PublishWorkflowSnapshot reconcileFullVersionPublishMechanics(PublishWorkflowRequ } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } - VersionAssetArtifactStateDto stagedArtifact; - try { - stagedArtifact = - versionAssetArtifactService.stageExport( - request.tenantId(), - version.getId(), - dto.versionNumber(), - request.publishWorkflowId()); - } catch (RuntimeException ex) { - throw pendingReconciliation( - "asset export staging outcome is pending; retry exact publish request", ex); - } - if (stagedArtifact == null - || !Objects.equals(stagedArtifact.tenantId(), request.tenantId()) - || !Objects.equals(stagedArtifact.versionId(), version.getId()) - || stagedArtifact.exportedVersionNumber() != dto.versionNumber() - || !Objects.equals(stagedArtifact.lastWorkflowId(), request.publishWorkflowId()) - || stagedArtifact.stateEpoch() <= 0 - || !("STAGED".equals(stagedArtifact.artifactState()) - || "EXPORTED_UNATTESTED".equals(stagedArtifact.artifactState()))) { - throw pendingReconciliation( - "asset export staging did not confirm the exact pending publish scope; " - + "retry the exact publish request"); + if (existingPublication.isAbsent()) { + try { + VersionAssetArtifactStateDto staged = + versionAssetArtifactService.stageExport( + request.tenantId(), dto.id(), dto.versionNumber(), request.publishWorkflowId()); + VersionAssetArtifactStateDto stagedReadback = + versionAssetArtifactService + .findState(request.tenantId(), dto.id()) + .orElseThrow(() -> pendingReconciliation("asset export intent readback is absent")); + if (staged == null || !staged.equals(stagedReadback)) { + throw pendingReconciliation("asset export intent readback does not match its commit"); + } + verifyStagedIntent(request, attempt, version, stagedReadback); + } catch (RuntimeException ex) { + throw pendingReconciliation("asset export intent commit requires exact readback", ex); + } } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); } catch (AssetExportOutcomePendingException ex) { throw pendingReconciliation( - "asset export outcome is pending; retry exact publish request", ex); + "asset export outcome remains unresolved; retry exact request", ex); } catch (RuntimeException ex) { - return failDefinitively(request, attempt, version, null, ex); + // Export may have committed candidate evidence or earlier immutable objects before failing. + // A deterministic later conflict does not prove that every prior write is resolved. + throw pendingReconciliation("asset export requires exact candidate/write reconciliation", ex); } PublishWorkflowRequest effectiveRequest = request; @@ -265,6 +327,7 @@ private PublishWorkflowSnapshot replayTerminalAttempt( // Failed legacy attempts may retain only terminal evidence after their draft was deleted. // Validate their stable scope before returning the immutable terminal result. validateTerminalFullVersionAttempt(attempt, request); + if (request.intent() != null) publishAttemptRepository.requireNoPublicationOperation(attempt); return new PublishWorkflowSnapshot( attempt.getVersionId() == null ? 0L : attempt.getVersionId(), attempt.getVersionNumber(), @@ -305,27 +368,32 @@ private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { } private PublishAttempt createDraftAttempt(PublishWorkflowRequest request) { - Game game = - Optional.ofNullable(gameRepository.findByTenantIdForUpdate(request.tenantId())) - .orElseThrow(() -> new IllegalArgumentException("game not found")); + if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { + throw new IllegalArgumentException("game not found"); + } + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); Optional existingAttempt = - publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()); + publishAttemptRepository.findByPublishWorkflowIdForUpdate(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")); @@ -340,30 +408,36 @@ private PublishWorkflowSnapshot finalizeFullVersion( } PublishAttempt attempt = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(attempt, request); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - if (!readPublication(request, attempt).isComplete()) { + publishAttemptRepository.requirePublishedOperation(attempt); + PublicationReadback readback = readPublication(request, attempt, true); + if (!readback.isComplete()) { throw pendingReconciliation( "succeeded full-version attempt lacks exact committed release evidence"); } + assertCommittedBundleEvidence(request, readback); return succeededSnapshot(attempt); } if (attempt.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } - Version version = requireAttemptVersion(attempt, request); + var publicationOperation = publishAttemptRepository.requirePublicationPending(attempt); + + Version version = requireAttemptVersionForUpdate(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); if (existingPublication.isComplete()) { - assertCommittedBundleMayMarkSuccess(request, existingPublication); + assertCommittedBundleEvidence(request, existingPublication); recordedParticipantDigestService.recordVerifiedDigests( request.tenantId(), PublishType.FULL_VERSION, request.publishWorkflowId(), existingPublication.bundle().participantDigests()); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } if (existingPublication.isPartial()) { @@ -376,6 +450,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 = @@ -394,9 +471,10 @@ private PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), exportedManifest, generationConfigRevision, - participantDigests); + participantDigests, + publicationOperation); version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L)); version.setUpdatedAt(LocalDateTime.now()); versionRepository.save(version); versionAssetArtifactService.markPublished( @@ -408,6 +486,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( recordedParticipantDigestService.recordVerifiedDigests( dto.tenantId(), PublishType.FULL_VERSION, request.publishWorkflowId(), participantDigests); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } @@ -424,6 +503,7 @@ private PublishWorkflowSnapshot reconcileCommittedAttempt( private PublishWorkflowSnapshot replaySucceededAttempt( PublishWorkflowRequest request, PublishAttempt attempt) { + if (request.intent() != null) publishAttemptRepository.requirePublishedOperation(attempt); PublishedReleaseBundleDto bundle; try { bundle = readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); @@ -437,6 +517,9 @@ private PublishWorkflowSnapshot replaySucceededAttempt( } try { requireExactCommittedBundleIdentity(request, attempt, bundle); + if (request.intent() != null) { + assertCommittedBundleEvidence(request, readPublication(request, attempt, true)); + } } catch (RuntimeException ex) { throw pendingReconciliation( "succeeded full-version attempt release bundle identity does not match", ex); @@ -454,7 +537,7 @@ private void recordVerifiedAndSucceed( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); @@ -462,6 +545,12 @@ private void recordVerifiedAndSucceed( && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { throw pendingReconciliation("full-version attempt is no longer pending"); } + if (current.getStatus() == PublishAttemptStatus.PENDING) { + publishAttemptRepository.requirePublicationPending(current); + } else { + publishAttemptRepository.requirePublishedOperation(current); + } + requireAttemptVersionForUpdate(current, request); PublicationReadback currentReadback = readPublication(request, current); if (!currentReadback.isComplete()) { throw pendingReconciliation( @@ -470,7 +559,7 @@ private void recordVerifiedAndSucceed( if (!Objects.equals(bundle, currentReadback.bundle())) { throw pendingReconciliation("published release bundle changed during reconciliation"); } - assertCommittedBundleMayMarkSuccess(request, currentReadback); + assertCommittedBundleEvidence(request, currentReadback); recordedParticipantDigestService.recordVerifiedDigests( request.tenantId(), PublishType.FULL_VERSION, @@ -478,6 +567,7 @@ private void recordVerifiedAndSucceed( currentReadback.bundle().participantDigests()); if (current.getStatus() == PublishAttemptStatus.PENDING) { publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(current, true); } return null; }); @@ -490,22 +580,22 @@ private void recordVerifiedAndSucceed( } /** - * Revalidates durable publication evidence before it can bless an attempt as successful. + * Revalidates retained publication evidence against the same gate used before first success. * *

Readback proves that the bundle and artifact are structurally tied to this attempt, but it * does not by itself prove that the participant matrix, typed scope, digest schema/content, and - * recorded baseline still satisfy the canonical publication gate. Reconciliation must apply the - * same local contracts as the initial publication path and fail closed for malformed or legacy - * evidence. + * recorded baseline still satisfy the canonical publication gate. Malformed or legacy evidence + * still fails closed. This read does not renew publication authority or mutate lifecycle state. */ - private void assertCommittedBundleMayMarkSuccess( + private void assertCommittedBundleEvidence( PublishWorkflowRequest request, PublicationReadback readback) { if (!readback.isComplete() || readback.version() == null || readback.bundle() == null) { throw pendingReconciliation( "published release evidence is incomplete; readback/reconciliation is required"); } VersionDto versionDto = versionMapper.toDto(readback.version()); - PublishedReleaseBundleContract.requireSupportedSchemaForRead(readback.bundle()); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); + assertSelectedCommit(request, readback.bundle().participantDigests()); publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); recordedParticipantDigestService.assertMatchesRecordedDigests( request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests()); @@ -517,6 +607,18 @@ private PublishWorkflowSnapshot failDefinitively( Version version, ExportedAssetManifest exportedManifest, RuntimeException failure) { + if (exportedManifest != null) { + PublicationReadback readback; + try { + readback = readPublication(request, attempt); + } catch (RuntimeException readFailure) { + throw pendingReconciliation( + "exported candidate readback requires exact retry/reconciliation", readFailure); + } + if (readback.isComplete()) return reconcileCommittedAttempt(request, attempt); + throw pendingReconciliation( + "exported candidate requires exact retry/reconciliation", failure); + } String failureCode = publishFailureCode(failure); String failureMessage = publishFailureMessage(failure); try { @@ -527,35 +629,39 @@ private PublishWorkflowSnapshot failDefinitively( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); if (current.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } + publishAttemptRepository.requirePublicationPending(current); + requireAttemptVersionForUpdate(current, request); PublicationReadback readback = readPublication(request, current); if (!readback.isAbsent()) { - throw pendingReconciliation( - "publication failure has committed or partial release evidence; reconciliation is required"); - } - Version currentVersion = requireAttemptVersion(current, request); - if (exportedManifest != null) { - versionAssetArtifactService.markFailed( - request.tenantId(), - currentVersion.getId(), - currentVersion.getVersionNumber(), - request.publishWorkflowId(), - exportedManifest, - failureCode, - failureMessage); + if (!readback.isStagedNoRelease() || readback.candidate() != null) { + throw pendingReconciliation( + "publication failure has committed or partial release evidence; reconciliation is required"); + } } publishAttemptService.markFullVersionFailed( request.publishWorkflowId(), failureCode, failureMessage); + publishAttemptRepository.sealPublication(current, false); // Approved launch remap sets may reference this failed candidate, so retain the row. return Boolean.TRUE; }); } catch (PublishAttemptService.FullVersionTransactionException ex) { + PublicationReadback winningPublication; + try { + winningPublication = readPublication(request, attempt); + } catch (RuntimeException readFailure) { + readFailure.addSuppressed(ex.causeException()); + throw pendingReconciliation( + "full-version failure marking readback failed; reconciliation is required", + readFailure); + } + if (winningPublication.isComplete()) return reconcileCommittedAttempt(request, attempt); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ex.causeException()); @@ -564,7 +670,8 @@ private PublishWorkflowSnapshot failDefinitively( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ambiguousFailure); } - cleanupExportedAssets(request.tenantId(), version.getVersionNumber(), exportedManifest); + // Immutable candidate keys can be shared with another release. Retain them for the owner + // abandonment/reachability workflow; a failed publication is never deletion authority. return new PublishWorkflowSnapshot( attempt.getVersionId(), attempt.getVersionNumber(), @@ -579,70 +686,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"); } @@ -655,6 +713,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, @@ -697,8 +759,29 @@ private Version requireAttemptVersion(PublishAttempt attempt, PublishWorkflowReq return version; } + private Version requireAttemptVersionForUpdate( + PublishAttempt attempt, PublishWorkflowRequest request) { + validateFullVersionAttempt(attempt, request); + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(request.tenantId(), attempt.getVersionId()) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (!Objects.equals(version.getTenantId(), request.tenantId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.isScriptOnly()) { + throw new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match request"); + } + return version; + } + private PublicationReadback readPublication( PublishWorkflowRequest request, PublishAttempt attempt) { + return readPublication(request, attempt, false); + } + + private PublicationReadback readPublication( + PublishWorkflowRequest request, PublishAttempt attempt, boolean terminalReplay) { Optional version = versionRepository.findByTenantIdAndId(request.tenantId(), attempt.getVersionId()); if (version.isEmpty()) { @@ -708,73 +791,87 @@ private PublicationReadback readPublication( readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); VersionAssetArtifactStateDto artifact = readVersionAssetArtifactState(request.tenantId(), attempt.getVersionId()); - if (bundle == null - && isExactPendingStagedCandidate(request, attempt, version.get(), artifact)) { - return PublicationReadback.absent(); - } if (bundle == null && artifact == null && version.get().getVersionState() == VersionLifecycleState.DRAFT) { - return PublicationReadback.absent(); + return PublicationReadback.absent(version.get()); + } + if (bundle == null + && version.get().getVersionState() == VersionLifecycleState.DRAFT + && artifact != null) { + try { + ExportedAssetManifest candidate = + verifyStagedIntent(request, attempt, version.get(), artifact); + return PublicationReadback.stagedNoRelease(version.get(), artifact, candidate); + } catch (RuntimeException ex) { + return PublicationReadback.partial(); + } } if (bundle == null || artifact == null) { return PublicationReadback.partial(); } try { - PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); requireExactBundleEvidence(request, attempt, version.get(), bundle); requireExactArtifactEvidence(request, attempt, bundle, artifact); } catch (RuntimeException ex) { return PublicationReadback.partial(); } - if (version.get().getVersionState() != VersionLifecycleState.PUBLISHED) { + VersionLifecycleState state = version.get().getVersionState(); + boolean retainedTerminalState = + terminalReplay + && (state == VersionLifecycleState.ACTIVE || state == VersionLifecycleState.RETIRED); + if (state != VersionLifecycleState.PUBLISHED && !retainedTerminalState) { return PublicationReadback.partial(); } return PublicationReadback.complete(version.get(), bundle, artifact); } - private boolean isExactPendingStagedCandidate( + private ExportedAssetManifest verifyStagedIntent( PublishWorkflowRequest request, PublishAttempt attempt, Version version, VersionAssetArtifactStateDto artifact) { - if (!(attempt.getPublishType() == PublishType.FULL_VERSION - && attempt.getStatus() == PublishAttemptStatus.PENDING - && Objects.equals(attempt.getTenantId(), request.tenantId()) - && Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) - && attempt.getVersionId() != null - && Objects.equals(version.getTenantId(), request.tenantId()) - && Objects.equals(version.getId(), attempt.getVersionId()) - && version.getVersionNumber() == attempt.getVersionNumber() - && version.getVersionState() == VersionLifecycleState.DRAFT - && !version.isScriptOnly() - && version.getVersionStateEpoch() != null - && version.getVersionStateEpoch() > 0 - && artifact != null - && Objects.equals(artifact.tenantId(), request.tenantId()) - && Objects.equals(artifact.versionId(), attempt.getVersionId()) - && artifact.exportedVersionNumber() == attempt.getVersionNumber() - && "STAGED".equals(artifact.artifactState()) - && artifact.stateEpoch() > 0 - && Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId()) - && artifact.lastErrorCode() == null - && artifact.lastErrorMessage() == null)) { - return false; + if (attempt.getPublishType() != PublishType.FULL_VERSION + || attempt.getStatus() != PublishAttemptStatus.PENDING + || !Objects.equals(attempt.getTenantId(), request.tenantId()) + || !Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) + || attempt.getVersionId() == null + || !Objects.equals(version.getTenantId(), request.tenantId()) + || !Objects.equals(version.getId(), attempt.getVersionId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.isScriptOnly() + || !Objects.equals(artifact.tenantId(), request.tenantId()) + || !Objects.equals(artifact.versionId(), attempt.getVersionId()) + || artifact.exportedVersionNumber() != attempt.getVersionNumber() + || !"STAGED".equals(artifact.artifactState()) + || artifact.stateEpoch() <= 0 + || !Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId()) + || artifact.lastErrorCode() != null + || artifact.lastErrorMessage() != null + || artifact.exportedManifestAssetKeys() == null) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_ARTIFACT_SCOPE_MISMATCH"); } - try { - ExportedAssetManifest candidate = - versionAssetArtifactService.getExportCandidate( - request.tenantId(), attempt.getVersionId()); - return candidate == null - && artifact.manifestHash() == null - && artifact.exportedManifestAssetKeys() != null - && artifact.exportedManifestAssetKeys().isEmpty(); - } catch (RuntimeException malformedOrAmbiguousCandidate) { - // Candidate evidence is not a committed release. Any unreadable or contradictory candidate - // remains reconciliation-required rather than being treated as an empty staged intent. - return false; + ExportedAssetManifest candidate = + versionAssetArtifactService.getExportCandidate(request.tenantId(), attempt.getVersionId()); + if (artifact.manifestHash() == null) { + if (!artifact.exportedManifestAssetKeys().isEmpty() || candidate != null) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); + } + return null; + } + if (candidate == null + || candidate.manifestSchemaVersion() != 1 + || !Objects.equals(candidate.manifestHash(), artifact.manifestHash()) + || !Objects.equals( + candidate.requiredManifestAssetKeys(), artifact.exportedManifestAssetKeys())) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); } + return candidate; } private void requireExactBundleEvidence( @@ -785,7 +882,12 @@ private void requireExactBundleEvidence( requireExactCommittedBundleIdentity(request, attempt, bundle); if (!Objects.equals(version.getTenantId(), bundle.tenantId()) || version.getVersionNumber() != bundle.versionNumber() - || version.isScriptOnly()) { + || version.isScriptOnly() + || (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion()) + && (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId()) + || !Objects.equals( + version.getCanonicalVersionId(), bundle.canonicalVersionId())))) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } } @@ -800,6 +902,39 @@ private void requireExactCommittedBundleIdentity( || bundle.scriptPatchVersion() != null) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); + requireExactSelectedWorldEvidence(request, bundle); + } + } + + private void requireExactSelectedWorldEvidence( + PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) { + // The stored owner payload is historical readback. It does not reconstruct a missing current + // owner freeze/Account permission producer or authorize another publication. + AuthoredDraftPublishSelection selected = requireSelectedIntent(request); + var evidence = bundle.worldPublishedStartLocationEvidence(); + var worldRequest = evidence.request(); + var account = DraftAuthorizationFenceBinding.fromStored(evidence.originalAccountBindingBytes()); + byte[] originalDraft = account.gameDesignBinding(); + if (!Arrays.equals(originalDraft, selected.selectedCommit().canonicalBytes()) + || !Arrays.equals(account.normalizedInput(), originalDraft) + || !selected.intent().selectedCommitDigest().equals(account.inputDigest()) + || !selected.intent().selectedCommitRequestId().equals(account.requestId()) + || !selected.intent().selectedCommitId().equals(account.commitId()) + || !selected.target().canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(worldRequest.canonicalVersionId()) + || !selected.target().canonicalTenantId().equals(bundle.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(bundle.canonicalVersionId()) + || !selected.intent().publishRequestId().equals(worldRequest.publicationRequestId()) + || !request.publishWorkflowId().equals(worldRequest.publishWorkflowId()) + || !selected + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(worldRequest.versionStateEpoch()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_WORLD_SELECTION_MISMATCH"); + } } private void requireExactArtifactEvidence( @@ -807,6 +942,22 @@ private void requireExactArtifactEvidence( PublishAttempt attempt, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { + // Retained terminal history is not backfilled into a complete asset attestation. For a new + // proof-bearing bundle, recovery must compare every original artifact/schema field too. + if (bundle.manifestSchemaVersion() != null) { + ExportedAssetManifest expected = + new ExportedAssetManifest( + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + bundle.artifactDigests()); + if (!Objects.equals( + expected, + versionAssetArtifactService.getExportCandidate( + request.tenantId(), attempt.getVersionId()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_ARTIFACT_SCOPE_MISMATCH"); + } + } if (!Objects.equals(artifact.tenantId(), request.tenantId()) || !Objects.equals(artifact.versionId(), attempt.getVersionId()) || artifact.exportedVersionNumber() != attempt.getVersionNumber() @@ -857,18 +1008,25 @@ private record PublicationReadback( ReadbackState state, Version version, PublishedReleaseBundleDto bundle, - VersionAssetArtifactStateDto artifact) { - private static PublicationReadback absent() { - return new PublicationReadback(ReadbackState.ABSENT, null, null, null); + VersionAssetArtifactStateDto artifact, + ExportedAssetManifest candidate) { + private static PublicationReadback absent(Version version) { + return new PublicationReadback(ReadbackState.ABSENT, version, null, null, null); } private static PublicationReadback partial() { - return new PublicationReadback(ReadbackState.PARTIAL, null, null, null); + return new PublicationReadback(ReadbackState.PARTIAL, null, null, null, null); + } + + private static PublicationReadback stagedNoRelease( + Version version, VersionAssetArtifactStateDto artifact, ExportedAssetManifest candidate) { + return new PublicationReadback( + ReadbackState.STAGED_NO_RELEASE, version, null, artifact, candidate); } private static PublicationReadback complete( Version version, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { - return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact); + return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact, null); } private boolean isAbsent() { @@ -879,6 +1037,10 @@ private boolean isPartial() { return state == ReadbackState.PARTIAL; } + private boolean isStagedNoRelease() { + return state == ReadbackState.STAGED_NO_RELEASE; + } + private boolean isComplete() { return state == ReadbackState.COMPLETE; } @@ -886,16 +1048,71 @@ private boolean isComplete() { private enum ReadbackState { ABSENT, + STAGED_NO_RELEASE, PARTIAL, 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) { + throw new IllegalStateException( + "PUBLISH_OWNER_CARRIER_UNAVAILABLE: current Account authorization and authenticated selected-source owner freeze are unavailable"); + } + } + + 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) { @@ -948,23 +1165,6 @@ private RuntimeException publishFailure(String failureCode, String failureMessag : failureMessage); } - private void cleanupExportedAssets( - String tenantId, int versionNumber, ExportedAssetManifest exportedManifest) { - if (exportedManifest == null) { - return; - } - try { - assetExportService.deleteExportedAssets( - tenantId, versionNumber, exportedManifest.requiredManifestAssetKeys()); - } catch (RuntimeException cleanupEx) { - logger.warn( - "Failed cleanup of exported assets for tenant {} version {} after publish failure: {}", - tenantId, - versionNumber, - cleanupEx.getMessage()); - } - } - private Version requireTenantVersion(String tenantId, long versionId) { return versionRepository .findByTenantIdAndId(tenantId, 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 5c20efee88..61db98cdfe 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; @@ -121,19 +122,23 @@ 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); - if (temporalPublishOrchestrator.isPresent()) { - return temporalPublishOrchestrator - .get() - .publishFullVersion(tenantId, notes, publishRequestId); - } - return publishCommandService.publishFullVersion( - tenantId, - notes, - publishRequestId, - TemporalVersionPublishOrchestrator.workflowId(tenantId, publishRequestId)); + public VersionDto publishVersion(PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + // Admin role and caller-selected commit identifiers do not prove current creator authority or + // the authenticated owner freeze required by full-version publication. + throw new IllegalStateException( + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: exact current Account authorization and owner freeze are required"); + } + + @Override + @Timed(value = "gamedesign.version.replayLegacyFullVersion") + public VersionDto replayLegacyFullVersion( + String tenantId, String notes, String publishRequestId) { + String workflowId = TemporalVersionPublishOrchestrator.workflowId(tenantId, publishRequestId); + // The command permits this old request shape only when the exact workflow already has a + // terminal attempt. A fresh or pending legacy request has no selected immutable source and + // is rejected before export, finalization, or attempt creation. + return publishCommandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); } @Override diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 4c8251d4e5..170ec88282 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -51,6 +51,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index cfa32714ea..3ee2e497fc 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -62,6 +62,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies http: enabled: true role-requirement: PRIVILEGED @@ -79,3 +81,6 @@ firemud: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + game-design: + published-realm-entry-policy-read: + enabled: ${FIREMUD_PUBLISHED_REALM_ENTRY_POLICY_READ_ENABLED:false} diff --git a/services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql b/services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql new file mode 100644 index 0000000000..aee294ac4a --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql @@ -0,0 +1,480 @@ +CREATE TABLE game_design_command_source_baseline ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + baseline_kind VARCHAR(32) NOT NULL, + receipt_id UUID NOT NULL, + creation_transaction_id TEXT NOT NULL, + target_proof_json TEXT NOT NULL, + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + UNIQUE (receipt_id), + UNIQUE (game_design_version_row_id), + 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, + FOREIGN KEY (game_design_version_row_id) + REFERENCES game_design_realm_policy_version_insert (version_id) ON DELETE RESTRICT, + CHECK (baseline_kind = 'NEW_DRAFT_EMPTY'), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_command_source_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id), + 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, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + operations_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + 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, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_operation ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), + revision_id UUID NOT NULL, + operation_kind VARCHAR(16) NOT NULL CHECK (operation_kind IN ('UPSERT', 'DELETE')), + command_id TEXT NOT NULL CHECK (char_length(command_id) > 0), + command_key TEXT NOT NULL CHECK (char_length(command_key) > 0), + definition_json TEXT, + operation_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + UNIQUE (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + CHECK (revision_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK ((operation_kind = 'UPSERT' AND definition_json IS NOT NULL) + OR (operation_kind = 'DELETE' AND definition_json IS NULL)) +); + +CREATE TABLE game_design_command_source_head ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + applied_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_command_source_baseline (canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE + REFERENCES game_design_publication_operation (publish_workflow_id) ON DELETE RESTRICT, + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE game_design_command_source_application + ADD CONSTRAINT command_source_application_json_shape CHECK ( + jsonb_typeof(snapshot_json::JSONB) = 'object' + AND jsonb_typeof(operations_json::JSONB) = 'array' + AND jsonb_array_length(operations_json::JSONB) > 0); +ALTER TABLE game_design_command_source_operation + ADD CONSTRAINT command_source_operation_json_shape CHECK ( + jsonb_typeof(operation_json::JSONB) = 'object'); + +CREATE FUNCTION guard_command_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; binding game_design_draft_commit%ROWTYPE; + witness game_design_realm_policy_version_insert%ROWTYPE; source_head game_design_command_source_head%ROWTYPE; + owner_result game_design_draft_commit_owner_result%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; snapshot game_design_command_source_snapshot%ROWTYPE; + expected BYTEA; payload BYTEA; receipt JSONB; proof JSONB; stored_operation JSONB; revision_payload JSONB; + revision_payload_text TEXT; declared_command_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'command source evidence cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO STRICT owner_version 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 = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF v; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'command source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_baseline' THEN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source baseline is immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert + WHERE version_id = NEW.game_design_version_row_id; + proof := NEW.target_proof_json::JSONB; + receipt := convert_from(NEW.receipt_bytes, 'UTF8')::JSONB; + IF NEW.baseline_kind <> 'NEW_DRAFT_EMPTY' OR owner_version.id <> NEW.game_design_version_row_id + OR owner_version.version_state_epoch <> 1 OR witness.creation_transaction_id <> NEW.creation_transaction_id + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR proof->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR proof->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR proof->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR proof->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR proof->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR proof->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR proof->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind + OR jsonb_typeof(proof) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(proof)) <> 7 + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 4 + OR receipt->>'schema' IS DISTINCT FROM 'game-design-command-source-new-draft-genesis/v1' + OR receipt->'targetProof' IS DISTINCT FROM proof + OR receipt->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR receipt->>'creationTransactionId' IS DISTINCT FROM NEW.creation_transaction_id THEN + RAISE EXCEPTION 'command source baseline lacks exact fresh Version insertion evidence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_head' THEN + IF TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL OR NEW.applied_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_baseline b + WHERE b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.canonical_version_id = NEW.canonical_version_id + AND b.receipt_digest = NEW.baseline_digest) THEN + RAISE EXCEPTION 'command source head must start at its exact empty Draft baseline' 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.baseline_digest IS DISTINCT FROM OLD.baseline_digest + OR EXISTS (SELECT 1 FROM game_design_command_source_capture c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id AND c.canonical_version_id = NEW.canonical_version_id) + OR 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 'command source head is frozen or its identity changed' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR NEW.applied_commit_id IS NULL OR NEW.applied_commit_id IS NOT DISTINCT FROM OLD.applied_commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.applied_commit_id + AND a.expected_epoch = OLD.source_epoch) THEN + RAISE EXCEPTION 'command source staged epoch must advance by its exact application' USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN + RAISE EXCEPTION 'command source applied pointer changes only with an epoch advance' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.visible_commit_id; + IF snapshot.inherited_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR snapshot.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = snapshot.request_id AND f.commit_id = snapshot.commit_id + AND f.input_digest = snapshot.input_digest AND c.workflow_state = 'SYNCHRONIZED' + AND v.request_id = f.request_id AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest) THEN + RAISE EXCEPTION 'command source visibility must advance to the exact synchronized coordinator fence' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; + END IF; + + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source history is immutable' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' + OR TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT binding 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; + IF binding.binding_json IS DISTINCT FROM NEW.binding_json OR binding.input_digest IS DISTINCT FROM NEW.input_digest THEN + RAISE EXCEPTION 'command source differs from exact Draft binding' USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF source_head.source_epoch IS DISTINCT FROM NEW.expected_epoch + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR 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) + OR NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR jsonb_typeof(NEW.operations_json::JSONB) IS DISTINCT FROM 'array' + OR jsonb_array_length(NEW.operations_json::JSONB) = 0 THEN + RAISE EXCEPTION 'command application must bind exact predecessor, baseline, epoch, and complete set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_operation' THEN + SELECT * INTO STRICT binding 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.commit_id = NEW.commit_id AND EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = c.canonical_tenant_id AND a.canonical_version_id = c.canonical_version_id + AND a.commit_id = c.commit_id); + SELECT rev->>'payload' INTO STRICT revision_payload_text FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') rev + WHERE rev->>'revisionOrder' = NEW.revision_order::TEXT AND rev->>'revisionId' = NEW.revision_id::TEXT + AND rev->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + revision_payload := revision_payload_text::JSONB; + stored_operation := NEW.operation_json::JSONB; + IF revision_payload->>'revisionKind' IS DISTINCT FROM 'COMMAND_DEFINITION' + OR revision_payload->>'schemaVersion' IS DISTINCT FROM '1' + OR (SELECT count(*) FROM jsonb_object_keys(revision_payload)) <> 4 + OR revision_payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR (SELECT count(*) FROM jsonb_object_keys(stored_operation)) + <> (CASE WHEN NEW.operation_kind = 'UPSERT' THEN 6 ELSE 5 END) + OR stored_operation->>'revisionOrder' IS DISTINCT FROM NEW.revision_order::TEXT + OR stored_operation->>'revisionId' IS DISTINCT FROM NEW.revision_id::TEXT + OR stored_operation->>'commitId' IS DISTINCT FROM NEW.commit_id::TEXT + OR stored_operation->>'operation' IS DISTINCT FROM NEW.operation_kind + OR stored_operation->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command operation must retain its exact authored revision identity' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.operation_kind = 'UPSERT' THEN + IF revision_payload->>'definitionJson' IS DISTINCT FROM NEW.definition_json + OR revision_payload->>'definitionJson' IS DISTINCT FROM stored_operation->>'definitionJson' + OR NEW.definition_json::JSONB->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command upsert definition differs from digest-bound authored payload' USING ERRCODE = 'check_violation'; + END IF; + ELSIF revision_payload->>'commandId' IS DISTINCT FROM NEW.command_id + OR revision_payload ? 'definitionJson' OR stored_operation ? 'definitionJson' THEN + RAISE EXCEPTION 'command delete must retain explicit identity without inferred absence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + SELECT count(*) INTO declared_command_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF (declared_command_count > 0) IS DISTINCT FROM (EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id)) THEN + RAISE EXCEPTION 'command-bearing synchronized commit requires its exact staged command application' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR source_head.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, 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 + AND f.input_digest = NEW.input_digest AND v.request_id = f.request_id + AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest AND c.workflow_state = 'SYNCHRONIZED') THEN + RAISE EXCEPTION 'command snapshot must retain complete source at exact synchronized fence' USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) THEN + RAISE EXCEPTION 'command snapshot differs from exact staged application' USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id) + AND coalesce(NEW.snapshot_json::JSONB->'definitions', '[]'::JSONB) + IS DISTINCT FROM coalesce((SELECT s.snapshot_json::JSONB->'definitions' + FROM game_design_command_source_snapshot s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.commit_id = NEW.inherited_commit_id), '[]'::JSONB) THEN + RAISE EXCEPTION 'disjoint synchronized commit must inherit exact complete command set' USING ERRCODE = 'check_violation'; + END IF; + 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 'command source is frozen by publication selection' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR source_head.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR source_head.source_epoch IS DISTINCT FROM snapshot.source_epoch + OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'command capture must bind actual pending operation and exact selected synchronized source' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'command capture bytes differ from immutable source and operation' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_command_source_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; owner_result game_design_draft_commit_owner_result%ROWTYPE; + source_head game_design_command_source_head%ROWTYPE; + expected BYTEA; payload BYTEA; operation_count BIGINT; declared_count BIGINT; mutation_count BIGINT; +BEGIN + SELECT * INTO STRICT binding 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; + SELECT * INTO STRICT owner_result FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO operation_count FROM game_design_command_source_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT jsonb_array_length(NEW.operations_json::JSONB) INTO declared_count; + SELECT count(*) INTO mutation_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF owner_result.status <> 'APPLIED' OR owner_result.result_commit_id <> NEW.commit_id + OR owner_result.result_binding_digest <> binding.input_digest OR declared_count <> operation_count + OR mutation_count <> operation_count + OR source_head.source_epoch IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR source_head.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR owner_result.applied_units_json IS NULL + OR NOT owner_result.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'COMMAND_DEFINITION_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'COMMAND_DEFINITION_SET', 'scopeId', 'effective', + 'expectedEpoch', NEW.expected_epoch, + 'resultingEpoch', (NEW.expected_epoch::NUMERIC + 1)::TEXT)) THEN + RAISE EXCEPTION 'command application requires exact combined control-plane APPLIED owner outcome' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(coalesce(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.operations_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.result_bytes THEN + RAISE EXCEPTION 'command application result bytes do not encode exact mutation and effective snapshot' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER command_source_baseline_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_baseline + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_application + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_operation + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_head + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE CONSTRAINT TRIGGER command_source_application_commit_guard AFTER INSERT ON game_design_command_source_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_command_source_application_commit(); + +CREATE FUNCTION deny_command_source_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'command source evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER command_source_baseline_no_truncate BEFORE TRUNCATE ON game_design_command_source_baseline + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_snapshot_no_truncate BEFORE TRUNCATE ON game_design_command_source_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_application_no_truncate BEFORE TRUNCATE ON game_design_command_source_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_operation_no_truncate BEFORE TRUNCATE ON game_design_command_source_operation + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_head_no_truncate BEFORE TRUNCATE ON game_design_command_source_head + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_capture_no_truncate BEFORE TRUNCATE ON game_design_command_source_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql b/services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql new file mode 100644 index 0000000000..e33d79335d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql @@ -0,0 +1,171 @@ +-- New reviewed claims only. Existing opaque bindings and retained history are not backfilled. +CREATE TABLE game_design_reviewed_draft_base ( + 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, + base_kind VARCHAR(32) NOT NULL CHECK (base_kind IN ('GENESIS', 'AUTHORED_COMMIT')), + base_identity UUID NOT NULL CHECK (base_identity <> '00000000-0000-0000-0000-000000000000'), + base_reference VARCHAR(44) NOT NULL, + evidence_schema VARCHAR(64) NOT NULL CHECK (evidence_schema = 'game-design-reviewed-draft-base/v1'), + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) > 0), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, request_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id), + 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, + CHECK (base_reference = CASE WHEN base_kind = 'GENESIS' THEN 'genesis:' ELSE '' END || base_identity::TEXT) +); + +-- [jooq ignore start] +CREATE FUNCTION game_design_reviewed_base_frame(value BYTEA) RETURNS BYTEA +LANGUAGE SQL IMMUTABLE STRICT AS $$ SELECT int4send(octet_length(value)) || value $$; +CREATE FUNCTION game_design_reviewed_base_frame(value TEXT) RETURNS BYTEA +LANGUAGE SQL IMMUTABLE STRICT AS $$ SELECT game_design_reviewed_base_frame(convert_to(value, 'UTF8')) $$; + +CREATE FUNCTION protect_game_design_reviewed_base() RETURNS trigger AS $$ +DECLARE + claim game_design_draft_commit%ROWTYPE; + owner_version version%ROWTYPE; + policy_genesis game_design_realm_policy_genesis%ROWTYPE; + command_genesis game_design_command_source_baseline%ROWTYPE; + witness game_design_realm_policy_version_insert%ROWTYPE; + base game_design_draft_commit%ROWTYPE; + policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + command_snapshot game_design_command_source_snapshot%ROWTYPE; + fence game_design_draft_commit_visibility_fence%ROWTYPE; + owner_result game_design_draft_commit_owner_result%ROWTYPE; + owner_name TEXT; + outcome JSONB; + epoch JSONB; + source_bytes BYTEA; + expected_bytes BYTEA; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Reviewed Draft base evidence is immutable'; + END IF; + SELECT * INTO STRICT claim 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; + SELECT * INTO STRICT owner_version FROM version WHERE id = claim.game_design_version_row_id FOR UPDATE; + IF claim.binding_json IS DISTINCT FROM NEW.binding_json OR claim.input_digest IS DISTINCT FROM NEW.input_digest + OR claim.base_commit_id IS DISTINCT FROM NEW.base_reference OR claim.workflow_state <> 'QUEUED' + OR EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.request_id = NEW.request_id AND r.status <> 'NOT_ATTEMPTED') + OR 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 + AND s.request_id = NEW.request_id) + OR owner_version.version_state <> 'DRAFT' + OR owner_version.is_script_only OR owner_version.base_version_id IS NOT NULL + OR owner_version.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'Reviewed base requires exact new full Draft binding'; + END IF; + IF NEW.base_kind = 'GENESIS' THEN + SELECT * INTO STRICT policy_genesis FROM game_design_realm_policy_genesis + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND receipt_id = NEW.base_identity AND version_id = claim.game_design_version_row_id; + SELECT * INTO STRICT command_genesis FROM game_design_command_source_baseline + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND receipt_id = NEW.base_identity AND game_design_version_row_id = claim.game_design_version_row_id; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert + WHERE version_id = claim.game_design_version_row_id; + IF policy_genesis.creation_transaction_id IS DISTINCT FROM witness.creation_transaction_id + OR command_genesis.creation_transaction_id IS DISTINCT FROM witness.creation_transaction_id + OR command_genesis.baseline_kind <> 'NEW_DRAFT_EMPTY' THEN + RAISE EXCEPTION 'Reviewed genesis must retain original shared receipt and insertion witness'; + END IF; + source_bytes := game_design_reviewed_base_frame('shared-policy-command-genesis/v1'::TEXT) + || game_design_reviewed_base_frame(witness.creation_transaction_id) + || game_design_reviewed_base_frame(convert_to(policy_genesis.receipt_json, 'UTF8')) + || game_design_reviewed_base_frame(command_genesis.receipt_bytes); + ELSE + SELECT * INTO STRICT base FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity; + SELECT * INTO STRICT fence FROM game_design_draft_commit_visibility_fence + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + SELECT * INTO STRICT policy_snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + SELECT * INTO STRICT command_snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + IF base.workflow_state <> 'SYNCHRONIZED' OR fence.input_digest IS DISTINCT FROM base.input_digest + OR command_snapshot.binding_json IS DISTINCT FROM base.binding_json + OR command_snapshot.input_digest IS DISTINCT FROM base.input_digest + OR policy_snapshot.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM base.binding_json + OR policy_snapshot.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM base.input_digest + OR (base.game_design_version_row_id, base.game_design_version_tenant_key, base.source_game_row_id, + base.source_game_tenant_key, base.source_provenance_kind) IS DISTINCT FROM + (claim.game_design_version_row_id, claim.game_design_version_tenant_key, claim.source_game_row_id, + claim.source_game_tenant_key, claim.source_provenance_kind) + OR jsonb_array_length(fence.result_vector_json::JSONB) <> + jsonb_array_length(base.binding_json::JSONB->'requiredOwners') THEN + RAISE EXCEPTION 'Reviewed authored base requires complete exact retained synchronized source'; + END IF; + source_bytes := game_design_reviewed_base_frame('retained-authored-policy-command-base/v1'::TEXT) + || game_design_reviewed_base_frame(convert_to(base.binding_json, 'UTF8')) + || game_design_reviewed_base_frame(convert_to(policy_snapshot.snapshot_json, 'UTF8')) + || game_design_reviewed_base_frame(convert_to(command_snapshot.snapshot_json, 'UTF8')) + || game_design_reviewed_base_frame(jsonb_array_length(base.binding_json::JSONB->'requiredOwners')::TEXT); + FOR owner_name IN SELECT jsonb_array_elements_text(base.binding_json::JSONB->'requiredOwners') LOOP + SELECT * INTO STRICT owner_result FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = base.request_id AND owner = owner_name; + SELECT item INTO STRICT outcome FROM jsonb_array_elements(fence.result_vector_json::JSONB) item + WHERE item->>'owner' = owner_name; + IF owner_result.status <> 'APPLIED' OR owner_result.result_commit_id IS DISTINCT FROM base.commit_id + OR owner_result.result_binding_digest IS DISTINCT FROM base.input_digest + OR outcome IS DISTINCT FROM jsonb_build_object('owner', owner_name, 'status', owner_result.status, + 'commitId', owner_result.result_commit_id::TEXT, 'bindingDigest', owner_result.result_binding_digest, + 'resultIdentity', owner_result.result_identity, + 'resultBytesBase64', replace(encode(owner_result.result_bytes, 'base64'), E'\n', ''), + 'appliedEpochs', owner_result.applied_units_json::JSONB) THEN + RAISE EXCEPTION 'Reviewed authored owner vector differs from retained exact outcome'; + END IF; + source_bytes := source_bytes || game_design_reviewed_base_frame(owner_name) + || game_design_reviewed_base_frame(owner_result.status::TEXT) + || game_design_reviewed_base_frame(base.commit_id::TEXT) + || game_design_reviewed_base_frame(base.input_digest::TEXT) + || game_design_reviewed_base_frame(owner_result.result_identity::TEXT) + || game_design_reviewed_base_frame(owner_result.result_bytes) + || game_design_reviewed_base_frame(jsonb_array_length(outcome->'appliedEpochs')::TEXT); + FOR epoch IN SELECT jsonb_array_elements(outcome->'appliedEpochs') LOOP + source_bytes := source_bytes || game_design_reviewed_base_frame(epoch->>'aggregateType') + || game_design_reviewed_base_frame(epoch->>'aggregateId') + || game_design_reviewed_base_frame(epoch->>'scopeType') + || game_design_reviewed_base_frame(epoch->>'scopeId') + || game_design_reviewed_base_frame(epoch->>'expectedEpoch') + || game_design_reviewed_base_frame(epoch->>'resultingEpoch'); + END LOOP; + END LOOP; + END IF; + expected_bytes := game_design_reviewed_base_frame(NEW.evidence_schema::TEXT) + || game_design_reviewed_base_frame('game-design-draft-base-reference/v1'::TEXT) + || game_design_reviewed_base_frame(NEW.base_kind::TEXT) + || game_design_reviewed_base_frame(NEW.base_reference::TEXT) + || game_design_reviewed_base_frame(NEW.canonical_tenant_id::TEXT) + || game_design_reviewed_base_frame(NEW.canonical_version_id::TEXT) + || game_design_reviewed_base_frame(claim.game_design_version_row_id::TEXT) + || game_design_reviewed_base_frame(claim.game_design_version_tenant_key::TEXT) + || game_design_reviewed_base_frame(claim.source_game_row_id::TEXT) + || game_design_reviewed_base_frame(claim.source_game_tenant_key::TEXT) + || game_design_reviewed_base_frame(claim.source_provenance_kind::TEXT) + || game_design_reviewed_base_frame(source_bytes); + IF NEW.evidence_bytes IS DISTINCT FROM expected_bytes + OR NEW.evidence_digest IS DISTINCT FROM 'sha256:' || encode(sha256(expected_bytes), 'hex') THEN + RAISE EXCEPTION 'Reviewed base bytes or digest differ from exact owner provenance'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_design_reviewed_base_protected + BEFORE INSERT OR UPDATE OR DELETE ON game_design_reviewed_draft_base + FOR EACH ROW EXECUTE FUNCTION protect_game_design_reviewed_base(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql b/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql new file mode 100644 index 0000000000..f654e77093 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql @@ -0,0 +1,97 @@ +-- Policy source heads have two distinct legal transitions: owner application stages the next +-- epoch while retaining the visible pointer, then synchronized capture advances only the pointer. +-- [jooq ignore start] +CREATE FUNCTION enforce_realm_policy_source_head_transition() RETURNS trigger AS $$ +BEGIN + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_application a + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = a.canonical_tenant_id + AND c.canonical_version_id = a.canonical_version_id + AND c.request_id = a.request_id + AND c.commit_id = a.commit_id + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_version_id = NEW.canonical_version_id + AND a.expected_epoch = OLD.source_epoch + AND a.inherited_commit_id IS NOT DISTINCT FROM OLD.visible_commit_id + AND a.genesis_receipt_id IS NOT DISTINCT FROM OLD.genesis_receipt_id + AND a.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + AND a.snapshot_json::JSONB->>'bindingJson' = c.binding_json + AND a.snapshot_json::JSONB->>'bindingDigest' = c.input_digest + AND (c.binding_json::JSONB->'requiredOwners') @> '["GAME_DESIGN_CONTROL_PLANE"]'::JSONB + AND ( + SELECT count(*) + FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') AS units(unit) + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'REALM_ENTRY_POLICY_SET' + ) = 1 + AND EXISTS ( + SELECT 1 + FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') AS units(unit) + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'REALM_ENTRY_POLICY_SET' + AND unit->>'aggregateId' = NEW.canonical_version_id::TEXT + AND unit->>'scopeType' = 'REALM_ENTRY_POLICY_SET' + AND unit->>'scopeId' = 'effective' + AND unit->>'expectedEpoch' = OLD.source_epoch + ) + AND EXISTS ( + SELECT 1 + FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') AS revisions(revision) + WHERE revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND ((revision->>'payload')::JSONB)->>'revisionKind' = 'REALM_ENTRY_POLICY' + ) + ) THEN + RAISE EXCEPTION 'realm policy source epoch must advance through its exact owner application' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch + OR NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_snapshot s + JOIN game_design_draft_commit_visibility_fence f + ON f.canonical_tenant_id = s.canonical_tenant_id + AND f.canonical_version_id = s.canonical_version_id + AND f.request_id = s.request_id + AND f.commit_id = s.commit_id + JOIN game_design_draft_commit_visibility v + ON v.canonical_tenant_id = f.canonical_tenant_id + AND v.canonical_version_id = f.canonical_version_id + AND v.request_id = f.request_id + AND v.commit_id = f.commit_id + 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 s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.commit_id = NEW.visible_commit_id + AND s.inherited_commit_id IS NOT DISTINCT FROM OLD.visible_commit_id + AND s.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + AND s.snapshot_json::JSONB->>'bindingJson' = c.binding_json + AND s.snapshot_json::JSONB->>'bindingDigest' = c.input_digest + AND f.input_digest = c.input_digest + AND v.input_digest = f.input_digest + AND c.workflow_state = 'SYNCHRONIZED' + ) THEN + RAISE EXCEPTION 'realm policy source pointer must advance to its exact current synchronized snapshot' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER realm_policy_source_head_transition_guard + BEFORE UPDATE ON game_design_realm_policy_source + FOR EACH ROW EXECUTE FUNCTION enforce_realm_policy_source_head_transition(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql new file mode 100644 index 0000000000..45dce1c2c4 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql @@ -0,0 +1,259 @@ +-- V1 preserves the exact V50.12 row-JSON bytes while excluding future additive columns. +-- Keep this explicit projection aligned with RELEASE_ROW_EVIDENCE_V1 in +-- GameDesignPublicationOperationRepository. The projection is intentionally not widened. +-- [jooq ignore start] +CREATE FUNCTION publication_release_row_evidence_v1(release_row published_release_bundle) RETURNS TEXT AS $$ + SELECT jsonb_build_object( + 'artifact_digests_json', release_row.artifact_digests_json, + 'attestation_schema_version', release_row.attestation_schema_version, + 'canonical_tenant_id', release_row.canonical_tenant_id, + 'canonical_version_id', release_row.canonical_version_id, + 'command_definitions_json', release_row.command_definitions_json, + 'generation_config_revision', release_row.generation_config_revision, + 'id', release_row.id, + 'manifest_hash', release_row.manifest_hash, + 'manifest_schema_version', release_row.manifest_schema_version, + 'participant_digests_json', release_row.participant_digests_json, + 'publish_workflow_id', release_row.publish_workflow_id, + 'published_at', release_row.published_at, + 'published_release_bundle_ref', release_row.published_release_bundle_ref, + 'required_manifest_asset_keys_json', release_row.required_manifest_asset_keys_json, + 'script_only', release_row.script_only, + 'script_patch_version', release_row.script_patch_version, + 'tenant_id', release_row.tenant_id, + 'version_id', release_row.version_id, + 'version_number', release_row.version_number, + 'world_published_start_location_evidence_json', release_row.world_published_start_location_evidence_json + )::TEXT; +$$ LANGUAGE SQL IMMUTABLE STRICT; + +-- Keep the V50.6 receipt framing and all publication, attempt, and Version gates unchanged. +CREATE OR REPLACE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT publication_release_row_evidence_v1(r) INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +-- Keep the V50.7 terminal framing, closed content projection, and committed-epoch checks unchanged. +CREATE OR REPLACE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR publication_release_row_evidence_v1(release) IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Preserve the complete V50.9 policy-set gate while using the same fixed release-row evidence. +CREATE OR REPLACE FUNCTION guard_published_realm_policy_set() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; owner_game game%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; + capture game_design_realm_policy_capture%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + release published_release_bundle%ROWTYPE; + row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published realm policy set is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.sealed IS DISTINCT FROM FALSE OR NEW.sealed IS DISTINCT FROM TRUE + OR (to_jsonb(NEW) - 'sealed') IS DISTINCT FROM (to_jsonb(OLD) - 'sealed') THEN + RAISE EXCEPTION 'published realm policy set may only be sealed once' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF row_count <> NEW.policy_count + OR row_count <> jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') + OR realm_count <> row_count OR production_count <> 1 + OR NEW.policy_set_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy set is incomplete or has invalid cardinality' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.sealed IS DISTINCT FROM FALSE + OR jsonb_typeof(NEW.target_proof_json::JSONB) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + SELECT count(*) INTO target_proof_key_count + FROM jsonb_object_keys(NEW.target_proof_json::JSONB); + IF target_proof_key_count <> 7 + OR (NEW.target_proof_json::JSONB - ARRAY['canonicalTenantId', 'canonicalVersionId', 'gameDesignVersionRowId', + 'gameDesignVersionTenantKey', 'sourceGameRowId', 'sourceGameTenantKey', 'sourceProvenanceKind']) + IS DISTINCT FROM '{}'::JSONB + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalVersionId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceProvenanceKind') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO owner_version 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.target_proof_json::JSONB->>'gameDesignVersionTenantKey' + 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::TEXT = NEW.target_proof_json::JSONB->>'sourceGameRowId' + AND v.identity_source_game_tenant_key = NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + AND v.identity_source_provenance_kind = NEW.target_proof_json::JSONB->>'sourceProvenanceKind'; + IF NOT FOUND OR owner_version.id IS DISTINCT FROM NEW.game_design_version_row_id + OR owner_version.version_state IS DISTINCT FROM 'PUBLISHED' + OR owner_version.version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR owner_version.version_number IS DISTINCT FROM NEW.version_number + OR owner_version.is_script_only IS DISTINCT FROM FALSE + OR owner_version.script_patch_version IS NOT NULL + OR owner_version.base_version_id IS NOT NULL + OR NEW.target_proof_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR NEW.target_proof_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.target_proof_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.target_proof_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.target_proof_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'published realm policy set differs from exact full Version owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT g.* INTO STRICT owner_game FROM game g WHERE g.id = owner_version.identity_source_game_row_id; + IF owner_game.id::TEXT IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameRowId' + OR owner_game.tenant_id IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + OR owner_game.tenant_identity_provenance_kind IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceProvenanceKind' + OR owner_game.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id THEN + RAISE EXCEPTION 'published realm policy set source provenance changed' USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set operation is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO capture FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set source capture is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT * INTO release FROM published_release_bundle + WHERE tenant_id = owner_version.tenant_id AND version_id = owner_version.id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set release bundle is unavailable' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome IS DISTINCT FROM 'PUBLISHED' + OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.terminal_evidence_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR operation.release_content_bytes IS DISTINCT FROM NEW.release_content_bytes + OR operation.published_release_bundle_digest IS DISTINCT FROM NEW.published_release_bundle_digest + OR operation.publication_version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR operation.tenant_id IS DISTINCT FROM owner_version.tenant_id + OR operation.version_id IS DISTINCT FROM owner_version.id + OR operation.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR capture.commit_id IS DISTINCT FROM NEW.source_commit_id + OR snapshot.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR publication_release_content(release) IS DISTINCT FROM NEW.release_content_bytes + OR 'sha256:' || encode(sha256(publication_release_content(release)), 'hex') + IS DISTINCT FROM NEW.published_release_bundle_digest + OR release.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR release.version_number IS DISTINCT FROM NEW.version_number + OR release.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR release.manifest_hash IS DISTINCT FROM NEW.manifest_hash + OR publication_release_row_evidence_v1(release) IS DISTINCT FROM operation.release_row_json + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.visible_commit_id = NEW.source_commit_id AND s.source_epoch = NEW.source_epoch) + OR 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.commit_id = NEW.source_commit_id) + OR jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') <> NEW.policy_count THEN + RAISE EXCEPTION 'published realm policy set is not bound to exact sealed operation, capture, source, and release' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql b/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql new file mode 100644 index 0000000000..5e8dc75c54 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql @@ -0,0 +1,94 @@ +-- Additive write guards only; retained source rows receive no inferred provenance or rewrite. +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_draft_commit_visibility_pointer_advance() RETURNS trigger AS $$ +BEGIN + 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 THEN + RAISE EXCEPTION 'Game Design Draft visibility pointer target is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.request_id IS NOT DISTINCT FROM OLD.request_id + AND NEW.commit_id IS NOT DISTINCT FROM OLD.commit_id + AND NEW.input_digest IS NOT DISTINCT FROM OLD.input_digest THEN + RETURN NEW; + END IF; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot s + ON s.canonical_tenant_id = c.canonical_tenant_id + AND s.canonical_version_id = c.canonical_version_id + AND s.request_id = c.request_id + AND s.commit_id = c.commit_id + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.request_id + AND c.commit_id = NEW.commit_id + AND c.workflow_state IN ('APPLYING', 'RECONCILIATION_REQUIRED') + ) THEN + RAISE EXCEPTION 'Draft visibility pointer may advance only to its actively applying commit' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_advance + BEFORE INSERT OR UPDATE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_pointer_advance(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_pointer_delete() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design Draft visibility pointers cannot be deleted' + USING ERRCODE = 'check_violation'; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_no_delete + BEFORE DELETE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION reject_gd_draft_commit_visibility_pointer_delete(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_pointer_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_visibility) THEN + RAISE EXCEPTION 'Game Design Draft visibility pointers cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_visibility + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_visibility_pointer_truncate(); + +CREATE FUNCTION enforce_realm_policy_source_head_insert_epoch() RETURNS trigger AS $$ +BEGIN + IF NEW.genesis_receipt_id IS NULL AND NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_snapshot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.commit_id = NEW.visible_commit_id + AND s.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + ) THEN + RAISE EXCEPTION 'realm policy source head must match its visible snapshot epoch' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_realm_policy_source_head_insert_epoch + BEFORE INSERT ON game_design_realm_policy_source + FOR EACH ROW + EXECUTE FUNCTION enforce_realm_policy_source_head_insert_epoch(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql b/services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql new file mode 100644 index 0000000000..4ca79b8bb1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql @@ -0,0 +1,123 @@ +-- Validate owner-set shape only for new bindings. Retained commits receive no inferred owners or rewrite. +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_draft_commit_required_owners() RETURNS trigger AS $$ +DECLARE + required_owners JSONB; +BEGIN + required_owners := NEW.binding_json::JSONB->'requiredOwners'; + IF jsonb_typeof(required_owners) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Draft commit requiredOwners must be a non-empty array of distinct known owner strings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(required_owners) = 0 THEN + RAISE EXCEPTION 'Draft commit requiredOwners must be a non-empty array of distinct known owner strings' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements(required_owners) AS required(owner) + WHERE jsonb_typeof(required.owner) IS DISTINCT FROM 'string' + OR required.owner #>> '{}' NOT IN ( + 'WORLD_MANAGEMENT', + 'ENTITY_MANAGEMENT', + 'GAME_LOGIC', + 'AUTOMATION_SCRIPTING', + 'GAME_DESIGN_CONTROL_PLANE' + ) + ) OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(required_owners) AS required(owner) + GROUP BY required.owner + HAVING count(*) > 1 + ) THEN + RAISE EXCEPTION 'Draft commit requiredOwners must be a non-empty array of distinct known owner strings' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_required_owners + BEFORE INSERT ON game_design_draft_commit + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_required_owners(); + +CREATE OR REPLACE 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 COALESCE((parent_record.binding_json::jsonb -> 'requiredOwners') ? NEW.owner, FALSE) 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; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql b/services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql new file mode 100644 index 0000000000..ec816e05b1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql @@ -0,0 +1,62 @@ +-- New source applications require the exact reviewed-base evidence reserved for their Draft. +-- Retained applications and historical bindings are not backfilled or rewritten. +-- [jooq ignore start] +CREATE FUNCTION require_reviewed_source_application_base() RETURNS trigger AS $$ +BEGIN + IF TG_TABLE_NAME = 'game_design_realm_policy_application' THEN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_reviewed_draft_base b + ON b.canonical_tenant_id = c.canonical_tenant_id + AND b.canonical_version_id = c.canonical_version_id + AND b.request_id = c.request_id + AND b.commit_id = c.commit_id + AND b.input_digest = c.input_digest + AND b.binding_json = c.binding_json + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.request_id + AND c.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Draft source application requires exact reviewed base evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF TG_TABLE_NAME = 'game_design_command_source_application' THEN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_reviewed_draft_base b + ON b.canonical_tenant_id = c.canonical_tenant_id + AND b.canonical_version_id = c.canonical_version_id + AND b.request_id = c.request_id + AND b.commit_id = c.commit_id + AND b.input_digest = c.input_digest + AND b.binding_json = c.binding_json + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.request_id + AND c.commit_id = NEW.commit_id + AND c.input_digest = NEW.input_digest + AND c.binding_json = NEW.binding_json + AND b.input_digest = NEW.input_digest + AND b.binding_json = NEW.binding_json + ) THEN + RAISE EXCEPTION 'Draft source application requires exact reviewed base evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Reviewed base guard is bound to an unsupported source application table' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER reviewed_realm_policy_application_guard + BEFORE INSERT ON game_design_realm_policy_application + FOR EACH ROW EXECUTE FUNCTION require_reviewed_source_application_base(); +CREATE TRIGGER reviewed_command_source_application_guard + BEFORE INSERT ON game_design_command_source_application + FOR EACH ROW EXECUTE FUNCTION require_reviewed_source_application_base(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql b/services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql new file mode 100644 index 0000000000..1dfcbba765 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.1__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_V29') + 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/V50.2__authored_draft_publish_selection.sql b/services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql new file mode 100644 index 0000000000..a1496e12a2 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.2__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_V29') + 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/main/resources/db/migration/V50.3__authored_draft_publish_request_identity.sql b/services/game-design-service/src/main/resources/db/migration/V50.3__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/V50.3__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/main/resources/db/migration/V50.4__selected_publish_attempt_digest_capacity.sql b/services/game-design-service/src/main/resources/db/migration/V50.4__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/V50.4__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/main/resources/db/migration/V50.5__game_design_draft_terminal_outcomes.sql b/services/game-design-service/src/main/resources/db/migration/V50.5__game_design_draft_terminal_outcomes.sql new file mode 100644 index 0000000000..6558e157d0 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.5__game_design_draft_terminal_outcomes.sql @@ -0,0 +1,405 @@ +-- Account-bound Game Design terminal readback is retained independently of coordinator workflow +-- status. Existing V42 rows are deliberately not backfilled: status-only history is not a receipt. +CREATE TABLE game_design_draft_terminal_operation ( + operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + fence_id UUID NOT NULL, + actor_account_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + expected_draft_epoch TEXT NOT NULL, + account_binding_bytes BYTEA NOT NULL, + account_binding_digest VARCHAR(71) NOT NULL, + game_design_binding_json TEXT NOT NULL, + game_design_input_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gd_draft_terminal_operation_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT uq_gd_draft_terminal_operation_fence UNIQUE (fence_id), + CONSTRAINT fk_gd_draft_terminal_operation_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_terminal_operation_ids CHECK ( + operation_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 fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND actor_account_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + AND expected_draft_epoch ~ '^(0|[1-9][0-9]*)$' + AND octet_length(account_binding_bytes) > 0 + ), + CONSTRAINT chk_gd_draft_terminal_operation_digests CHECK ( + account_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_design_input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_terminal_operation_binding CHECK ( + jsonb_typeof(game_design_binding_json::jsonb) = 'object' + ) +); + +CREATE TABLE game_design_draft_terminal_outcome ( + operation_id UUID NOT NULL, + outcome VARCHAR(32) NOT NULL, + owner_result_vector_json TEXT NOT NULL, + terminal_evidence_bytes BYTEA NOT NULL, + terminal_evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_outcome PRIMARY KEY (operation_id), + CONSTRAINT fk_gd_draft_terminal_outcome_operation FOREIGN KEY (operation_id) + REFERENCES game_design_draft_terminal_operation (operation_id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_terminal_outcome_kind CHECK ( + outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED') + ), + CONSTRAINT chk_gd_draft_terminal_outcome_evidence CHECK ( + octet_length(terminal_evidence_bytes) > 0 + AND terminal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND jsonb_typeof(owner_result_vector_json::jsonb) = 'array' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_terminal_vector_matches_owner_results( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID, + vector_json TEXT +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_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(vector_json::jsonb) IS DISTINCT FROM 'array' + OR jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + IF jsonb_array_length(vector_json::jsonb) <> 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) + WHERE NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(vector_json::jsonb) actual + JOIN game_design_draft_commit_owner_result stored + ON stored.canonical_tenant_id = target_tenant + AND stored.canonical_version_id = target_version + AND stored.request_id = target_request + AND stored.owner = required.owner + WHERE actual ->> 'owner' = required.owner + AND actual ->> 'status' = stored.status + AND actual ->> 'commitId' = stored.result_commit_id::text + AND actual ->> 'bindingDigest' = stored.result_binding_digest + AND actual ->> 'resultIdentity' = stored.result_identity + AND actual ->> 'resultBytesBase64' = replace(encode(stored.result_bytes, 'base64'), E'\n', '') + AND actual -> 'appliedEpochs' = stored.applied_units_json::jsonb + ) + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_terminal_operation() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Account operation bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT 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 THEN + RAISE EXCEPTION 'Account operation must claim an existing Game Design commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.input_digest IS DISTINCT FROM NEW.game_design_input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.game_design_binding_json + OR parent_record.workflow_state IS DISTINCT FROM 'QUEUED' + OR NEW.game_design_binding_json::jsonb ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.game_design_binding_json::jsonb ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.game_design_binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.game_design_binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.game_design_binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id THEN + RAISE EXCEPTION 'Account operation must claim the exact queued Game Design binding before dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 + FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id + AND slot.canonical_version_id = NEW.canonical_version_id + ) OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_owner_result owner_result + WHERE owner_result.canonical_tenant_id = NEW.canonical_tenant_id + AND owner_result.canonical_version_id = NEW.canonical_version_id + AND owner_result.request_id = NEW.request_id + AND owner_result.status <> 'NOT_ATTEMPTED' + ) THEN + RAISE EXCEPTION 'Account operation binding was not retained before owner dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM version v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.version_state = 'DRAFT' + ) THEN + RAISE EXCEPTION 'Account operation can be claimed only for the exact DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_operation + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_operation(); + +CREATE FUNCTION reject_gd_draft_terminal_operation_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_operation) THEN + RAISE EXCEPTION 'Game Design Account operation bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_operation + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_operation_truncate(); + +CREATE FUNCTION enforce_gd_draft_terminal_outcome() RETURNS trigger AS $$ +DECLARE + operation_record RECORD; + commit_record RECORD; + fence_record RECORD; + abort_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design terminal outcomes are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * + INTO operation_record + FROM game_design_draft_terminal_operation + WHERE operation_id = NEW.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact Account operation binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + SELECT workflow_state, input_digest, binding_json + INTO commit_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact coordinator commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF NOT gd_draft_terminal_vector_matches_owner_results( + operation_record.canonical_tenant_id, + operation_record.canonical_version_id, + operation_record.request_id, + operation_record.commit_id, + NEW.owner_result_vector_json + ) THEN + RAISE EXCEPTION 'Terminal outcome requires the complete exact retained owner result vector' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.outcome = 'COMMITTED' THEN + SELECT input_digest, result_vector_json + INTO fence_record + FROM game_design_draft_commit_visibility_fence + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Committed terminal outcome lacks its exact visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'SYNCHRONIZED' + OR fence_record.input_digest IS DISTINCT FROM operation_record.game_design_input_digest + OR fence_record.result_vector_json IS DISTINCT FROM NEW.owner_result_vector_json + OR NEW.terminal_evidence_bytes IS DISTINCT FROM convert_to(NEW.owner_result_vector_json, 'UTF8') + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Committed terminal outcome must match synchronized visibility and every APPLIED owner' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.outcome = 'DEFINITIVELY_ABORTED' THEN + SELECT abort_bytes + INTO abort_record + FROM game_design_draft_commit_final_abort + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Aborted terminal outcome lacks its exact final-abort tombstone' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'FAILED_NONPUBLICATION' + OR abort_record.abort_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_visibility_fence fence + WHERE fence.canonical_tenant_id = operation_record.canonical_tenant_id + AND fence.canonical_version_id = operation_record.canonical_version_id + AND fence.request_id = operation_record.request_id + AND fence.commit_id = operation_record.commit_id + ) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' NOT IN ('APPLIED', 'REJECTED') + ) THEN + RAISE EXCEPTION 'Aborted terminal outcome must match exact final-abort evidence and definitive participants' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Unknown Game Design terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_outcome + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_outcome(); + +CREATE FUNCTION reject_gd_draft_terminal_outcome_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_outcome) THEN + RAISE EXCEPTION 'Game Design terminal outcomes cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_outcome + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_outcome_truncate(); + +CREATE FUNCTION require_gd_draft_account_terminal_readback() RETURNS trigger AS $$ +DECLARE + current_commit RECORD; + operation_record RECORD; + terminal_record RECORD; + expected_outcome VARCHAR(32); +BEGIN + SELECT workflow_state, canonical_tenant_id, canonical_version_id, request_id, commit_id + INTO current_commit + 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 + RETURN NULL; + END IF; + IF current_commit.workflow_state NOT IN ('SYNCHRONIZED', 'FAILED_NONPUBLICATION', 'REJECTED') THEN + RETURN NULL; + END IF; + + SELECT operation_id + INTO operation_record + FROM game_design_draft_terminal_operation + 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; + IF NOT FOUND THEN + RETURN NULL; + END IF; + + IF current_commit.workflow_state = 'REJECTED' THEN + RAISE EXCEPTION 'Account-bound rejection is not a terminal readback; exact final-abort evidence is required' + USING ERRCODE = 'check_violation'; + END IF; + + expected_outcome := + CASE current_commit.workflow_state + WHEN 'SYNCHRONIZED' THEN 'COMMITTED' + ELSE 'DEFINITIVELY_ABORTED' + END; + SELECT outcome + INTO terminal_record + FROM game_design_draft_terminal_outcome + WHERE operation_id = operation_record.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + IF terminal_record.outcome IS DISTINCT FROM expected_outcome THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER trg_gd_draft_account_terminal_readback + AFTER UPDATE ON game_design_draft_commit + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION require_gd_draft_account_terminal_readback(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql b/services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql new file mode 100644 index 0000000000..056e74b3a5 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql @@ -0,0 +1,180 @@ +ALTER TABLE publish_attempt ADD COLUMN revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0); + +CREATE TABLE game_design_publication_operation ( + publish_workflow_id VARCHAR(1024) PRIMARY KEY REFERENCES publish_attempt(publish_workflow_id) ON DELETE RESTRICT, + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL REFERENCES version(id) ON DELETE RESTRICT, + selection_digest VARCHAR(71) NOT NULL, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + outcome TEXT NOT NULL DEFAULT 'PENDING' CHECK (outcome IN ('PENDING', 'PUBLISHED', 'NO_PUBLICATION')), + revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0), + result_bytes BYTEA, + release_row_json TEXT, + CHECK ((outcome = 'PENDING') = (result_bytes IS NULL)), + CHECK ((outcome = 'PUBLISHED') = (release_row_json IS NOT NULL)), + UNIQUE (tenant_id, version_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_design_publication_operation() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + account_bytes BYTEA; input_bytes BYTEA; world_json JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'publication operation history is immutable' USING ERRCODE = 'check_violation'; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id; + account_bytes := published_world_selector_frame(NEW.request_bytes, 1); + input_bytes := published_world_selector_frame(account_bytes, 3); + world_json := convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB; + IF convert_from(published_world_selector_frame(NEW.request_bytes, 0), 'UTF8') <> 'game-design-publication-operation/v1' + OR convert_from(published_world_selector_frame(account_bytes, 0), 'UTF8') <> 'account-publication-authorization/v1' + OR convert_from(published_world_selector_frame(input_bytes, 0), 'UTF8') <> 'account-publication-input/v1' + OR published_world_selector_frame(input_bytes, 2) IS DISTINCT FROM convert_to(selected.selection_json, 'UTF8') + OR convert_from(published_world_selector_frame(input_bytes, 3), 'UTF8') IS DISTINCT FROM selected.selection_digest + OR world_json->'request'->>'requestDigest' IS DISTINCT FROM substring(selected.selection_digest FROM 8) + OR world_json->'request'->>'canonicalTenantId' IS DISTINCT FROM selected.canonical_tenant_id::TEXT + OR world_json->'request'->>'canonicalVersionId' IS DISTINCT FROM selected.canonical_version_id::TEXT + OR world_json->'request'->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR world_json->'request'->>'publicationRequestId' IS DISTINCT FROM selected.publish_request_id + OR world_json->'request'->>'versionStateEpoch' IS DISTINCT FROM selected.version_state_epoch::TEXT THEN + RAISE EXCEPTION 'publication operation bytes differ from exact owner selection' USING ERRCODE = 'check_violation'; + END IF; + IF attempt.tenant_id <> NEW.tenant_id OR attempt.version_id <> NEW.version_id + OR attempt.publish_type <> 'FULL_VERSION' OR attempt.request_digest IS DISTINCT FROM NEW.selection_digest + OR NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.game_design_version_tenant_key = NEW.tenant_id + AND s.game_design_version_row_id = NEW.version_id AND s.selection_digest = NEW.selection_digest) THEN + RAISE EXCEPTION 'publication operation does not bind exact selected attempt' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.outcome <> 'PENDING' OR NEW.revision <> 1 OR attempt.status <> 'PENDING' + OR EXISTS (SELECT 1 FROM published_release_bundle WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id) THEN + RAISE EXCEPTION 'historical attempts cannot acquire publication authority' USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF OLD.outcome <> 'PENDING' OR NEW.outcome = 'PENDING' + OR NEW.revision <> OLD.revision + 1 + OR (NEW.publish_workflow_id, NEW.tenant_id, NEW.version_id, NEW.selection_digest, NEW.request_bytes) + IS DISTINCT FROM (OLD.publish_workflow_id, OLD.tenant_id, OLD.version_id, OLD.selection_digest, OLD.request_bytes) THEN + RAISE EXCEPTION 'publication operation identity or terminal outcome is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_design_publication_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_game_design_publication_operation(); + +CREATE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version <> 'v2' AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version <> 'v2' + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER selected_publication_release_guard BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION guard_selected_publication_release(); + +CREATE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT to_jsonb(r)::TEXT INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_operation_commit_guard AFTER INSERT OR UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_release_commit_guard AFTER INSERT + ON published_release_bundle DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_attempt_commit_guard AFTER UPDATE + ON publish_attempt DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); + +CREATE FUNCTION guard_publish_attempt_revision() RETURNS trigger AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.revision <> OLD.revision + 1 + OR (NEW.id, NEW.tenant_id, NEW.publish_workflow_id, NEW.publish_type, NEW.version_id, + NEW.version_number, NEW.script_patch_version, NEW.base_version_id, NEW.created_at) + IS DISTINCT FROM (OLD.id, OLD.tenant_id, OLD.publish_workflow_id, OLD.publish_type, OLD.version_id, + OLD.version_number, OLD.script_patch_version, OLD.base_version_id, OLD.created_at) + OR (NEW.request_digest IS DISTINCT FROM OLD.request_digest AND + (OLD.request_digest IS NOT NULL OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = OLD.tenant_id AND game_design_version_row_id = OLD.version_id))) THEN + RAISE EXCEPTION 'publish attempt is stale or terminal' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publish_attempt_revision_guard BEFORE UPDATE ON publish_attempt + FOR EACH ROW EXECUTE FUNCTION guard_publish_attempt_revision(); + +CREATE FUNCTION guard_sealed_candidate_admission() RETURNS trigger AS $$ +BEGIN + -- Private puts already in flight may finish; this guards admission/retained candidate changes, + -- not cancellation, reachability, abandonment, deletion, or distributed object-store writes. + IF NEW.artifact_state = 'STAGED' AND EXISTS (SELECT 1 FROM game_design_publication_operation + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id AND outcome <> 'PENDING') THEN + RAISE EXCEPTION 'sealed publication refuses candidate admission' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER sealed_candidate_admission_guard BEFORE INSERT OR UPDATE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_sealed_candidate_admission(); + +CREATE FUNCTION forbid_publication_operation_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'publication operation history cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_operation_no_truncate BEFORE TRUNCATE ON game_design_publication_operation + FOR EACH STATEMENT EXECUTE FUNCTION forbid_publication_operation_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.7__publication_terminal_content_and_epoch.sql b/services/game-design-service/src/main/resources/db/migration/V50.7__publication_terminal_content_and_epoch.sql new file mode 100644 index 0000000000..a40cd4fd14 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.7__publication_terminal_content_and_epoch.sql @@ -0,0 +1,141 @@ +-- Retained V50 terminal rows keep their original bytes and gain no unverifiable epoch. +ALTER TABLE game_design_publication_operation ADD COLUMN terminal_evidence_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN publication_version_state_epoch BIGINT; +ALTER TABLE game_design_publication_operation ADD COLUMN release_content_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN published_release_bundle_digest VARCHAR(71); +ALTER TABLE game_design_publication_operation ADD CONSTRAINT publication_terminal_extension_shape CHECK ( + (terminal_evidence_bytes IS NULL AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (terminal_evidence_bytes IS NOT NULL AND octet_length(terminal_evidence_bytes) > 0 AND + ((outcome = 'NO_PUBLICATION' AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (outcome = 'PUBLISHED' AND publication_version_state_epoch IS NOT NULL AND publication_version_state_epoch > 0 + AND release_content_bytes IS NOT NULL AND octet_length(release_content_bytes) > 0 + AND published_release_bundle_digest IS NOT NULL AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$')))); + +-- [jooq ignore start] +-- ADR byte-length framing for complete immutable release content, distinct from launch evidence. +CREATE FUNCTION publication_content_frame(value BYTEA) RETURNS BYTEA AS $$ + SELECT convert_to(octet_length(value)::TEXT || ':', 'UTF8') || value; +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_text(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_frame(convert_to(value, 'UTF8')); +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_optional(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_text(CASE WHEN value IS NULL THEN 'false' ELSE 'true' END) + || publication_content_text(COALESCE(value, '')); +$$ LANGUAGE SQL IMMUTABLE; +CREATE FUNCTION publication_content_strings(values_json JSONB) RETURNS BYTEA AS $$ +DECLARE result BYTEA; value JSONB; +BEGIN + result := publication_content_text(jsonb_array_length(values_json)::TEXT); + FOR value IN SELECT * FROM jsonb_array_elements(values_json) LOOP + result := result || publication_content_text(value #>> '{}'); + END LOOP; + RETURN result; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version <> 'v2' THEN + RAISE EXCEPTION 'terminal publication requires complete full-version v2 content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; + +CREATE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR to_jsonb(release)::TEXT IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_terminal_extension_guard BEFORE INSERT OR UPDATE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_publication_terminal_extension(); + +CREATE FUNCTION verify_publication_terminal_epoch_commit() RETURNS trigger AS $$ +BEGIN + IF NEW.outcome = 'PUBLISHED' AND NEW.terminal_evidence_bytes IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + AND version_state = 'PUBLISHED' AND version_state_epoch = NEW.publication_version_state_epoch) THEN + RAISE EXCEPTION 'publication terminal epoch lacks its exact atomic Version commit' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_terminal_epoch_commit_guard AFTER UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_terminal_epoch_commit(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql b/services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql new file mode 100644 index 0000000000..c391045127 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql @@ -0,0 +1,311 @@ +-- Explicit new-Draft genesis requires the Version's actual insertion transaction witness. +-- No retained backfill or inferred empty baseline is installed. +CREATE TABLE game_design_realm_policy_version_insert ( + version_id BIGINT PRIMARY KEY REFERENCES version (id), + creation_transaction_id TEXT NOT NULL CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_realm_policy_genesis ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + receipt_id UUID NOT NULL UNIQUE, + version_id BIGINT NOT NULL UNIQUE REFERENCES game_design_realm_policy_version_insert (version_id), + creation_transaction_id TEXT NOT NULL, + receipt_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000') +); + +CREATE TABLE game_design_realm_policy_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + snapshot_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + 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), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- PostgreSQL JSON extraction is unsupported by the jOOQ DDL simulation; retain the exact owner checks. +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_snapshot + ADD CONSTRAINT realm_policy_snapshot_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_snapshot_epoch CHECK (snapshot_json::JSONB->>'sourceEpoch' ~ '^(0|[1-9][0-9]*)$'), + ADD CONSTRAINT realm_policy_snapshot_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_source ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (visible_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +CREATE TABLE game_design_realm_policy_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + owner_result_bytes BYTEA, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + 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), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (inherited_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_application + ADD CONSTRAINT realm_policy_application_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_application_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION witness_realm_policy_version_insert() RETURNS trigger AS $$ +BEGIN + IF NEW.canonical_tenant_id IS NOT NULL AND NEW.canonical_version_id IS NOT NULL + AND NEW.version_state = 'DRAFT' AND NOT NEW.is_script_only + AND NEW.script_patch_version IS NULL AND NEW.base_version_id IS NULL THEN + INSERT INTO game_design_realm_policy_version_insert (version_id, creation_transaction_id) + VALUES (NEW.id, pg_current_xact_id()::TEXT); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_witness AFTER INSERT ON version + FOR EACH ROW EXECUTE FUNCTION witness_realm_policy_version_insert(); + +CREATE FUNCTION guard_realm_policy_genesis() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; witness game_design_realm_policy_version_insert%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'new-Draft insertion and genesis evidence is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_version_insert' THEN + IF pg_trigger_depth() < 2 OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'new-Draft witness requires the actual Version insertion trigger' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT owner_version FROM version WHERE id = NEW.version_id FOR UPDATE; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert WHERE version_id = NEW.version_id; + IF witness.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.creation_transaction_id <> witness.creation_transaction_id + OR NEW.canonical_tenant_id <> owner_version.canonical_tenant_id + OR NEW.canonical_version_id <> owner_version.canonical_version_id + OR owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL + OR EXISTS (SELECT 1 FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) + OR NEW.receipt_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-realm-policy-genesis/v1' + OR NEW.receipt_json::JSONB->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR NEW.receipt_json::JSONB->>'creationTransactionId' IS DISTINCT FROM witness.creation_transaction_id + OR NEW.receipt_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM owner_version.canonical_tenant_id::TEXT + OR NEW.receipt_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM owner_version.canonical_version_id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.receipt_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.receipt_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.receipt_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'realm policy genesis lacks the exact fresh owner insertion' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_version_insert + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); +CREATE TRIGGER realm_policy_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_genesis + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); + +CREATE FUNCTION guard_realm_policy_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; operation game_design_publication_operation%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + expected BYTEA; payload BYTEA; policies JSONB; source_binding game_design_draft_commit%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'realm policy source history cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT owner_version FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'realm policy source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF TG_TABLE_NAME = 'game_design_realm_policy_application' THEN + IF OLD.owner_result_bytes IS NOT NULL OR NEW.owner_result_bytes IS NULL + OR (to_jsonb(NEW) - 'owner_result_bytes') IS DISTINCT FROM (to_jsonb(OLD) - 'owner_result_bytes') THEN + RAISE EXCEPTION 'realm policy application permits only its one atomic complete owner result' USING ERRCODE = 'check_violation'; + END IF; + ELSIF TG_TABLE_NAME <> 'game_design_realm_policy_source' THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + ELSIF 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.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF EXISTS (SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'realm policy source is frozen' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_source' THEN + IF TG_OP = 'INSERT' AND NEW.genesis_receipt_id IS NOT NULL THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_genesis g WHERE g.receipt_id = NEW.genesis_receipt_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id AND g.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'genesis source must begin empty at its exact owner epoch zero' USING ERRCODE = 'check_violation'; + END IF; + END IF; + END IF; + IF TG_TABLE_NAME IN ('game_design_realm_policy_snapshot', 'game_design_realm_policy_application') THEN + SELECT * INTO STRICT source_binding 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; + policies := NEW.snapshot_json::JSONB->'policies'; + IF NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM source_binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM source_binding.input_digest + OR jsonb_typeof(policies) IS DISTINCT FROM 'array' + OR jsonb_array_length(policies) NOT BETWEEN 0 AND 128 + OR (SELECT count(DISTINCT p->'policy'->>'realmSlug') FROM jsonb_array_elements(policies) p) <> jsonb_array_length(policies) THEN + RAISE EXCEPTION 'realm policy snapshot lacks exact source binding or unique bounded selectors' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + policies := snapshot.snapshot_json::JSONB->'policies'; + IF jsonb_array_length(policies) NOT BETWEEN 1 AND 128 + OR (SELECT count(*) FROM jsonb_array_elements(policies) p WHERE p->'policy'->'visible' = 'true'::JSONB + AND p->'policy'->'publicProduction' = 'true'::JSONB) <> 1 + OR operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.visible_commit_id = NEW.commit_id + AND s.source_epoch = snapshot.snapshot_json::JSONB->>'sourceEpoch') + OR 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.commit_id = NEW.commit_id) THEN + RAISE EXCEPTION 'realm policy capture differs from original synchronized publication' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-realm-policy-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload + || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'realm policy capture bytes differ from immutable source' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER realm_policy_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_source_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_source + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_application + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_capture + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); + +CREATE FUNCTION verify_realm_policy_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; result game_design_draft_commit_owner_result%ROWTYPE; + expected BYTEA; payload BYTEA; application game_design_realm_policy_application%ROWTYPE; genesis game_design_realm_policy_genesis%ROWTYPE; +BEGIN + SELECT * INTO STRICT application FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT binding 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; + SELECT * INTO STRICT result FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + payload := convert_to('game-design-realm-policy-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.genesis_receipt_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := ''::BYTEA; + IF NEW.genesis_receipt_id IS NOT NULL THEN + SELECT * INTO STRICT genesis FROM game_design_realm_policy_genesis WHERE receipt_id = NEW.genesis_receipt_id; + IF genesis.canonical_tenant_id <> NEW.canonical_tenant_id OR genesis.canonical_version_id <> NEW.canonical_version_id THEN + RAISE EXCEPTION 'policy application changed genesis target' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to(genesis.receipt_json, 'UTF8'); + END IF; + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.inherited_commit_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(COALESCE(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF result.status <> 'APPLIED' OR application.owner_result_bytes IS NULL + OR result.result_bytes IS DISTINCT FROM application.owner_result_bytes OR NEW.result_bytes IS DISTINCT FROM expected + OR result.result_commit_id <> NEW.commit_id OR result.result_binding_digest <> binding.input_digest + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM binding.input_digest + OR (NEW.snapshot_json::JSONB->>'sourceEpoch')::NUMERIC <> NEW.expected_epoch::NUMERIC + 1 THEN + RAISE EXCEPTION 'realm policy application lacks atomic exact coordinator result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER realm_policy_application_commit_guard AFTER INSERT ON game_design_realm_policy_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_realm_policy_application_commit(); + +CREATE FUNCTION deny_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'realm policy owner evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_snapshot_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_source_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_source + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_application_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_capture_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_version_insert_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_version_insert + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_genesis_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_genesis + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql new file mode 100644 index 0000000000..80a635e3f7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql @@ -0,0 +1,278 @@ +CREATE TABLE game_design_published_realm_policy_set ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL CHECK (game_design_version_row_id > 0), + version_number INTEGER NOT NULL CHECK (version_number > 0), + source_commit_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + target_proof_json TEXT NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + release_content_bytes BYTEA NOT NULL CHECK (octet_length(release_content_bytes) > 0), + published_release_bundle_ref VARCHAR(1024) NOT NULL CHECK (char_length(published_release_bundle_ref) > 0), + published_release_bundle_digest VARCHAR(71) NOT NULL CHECK (published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$'), + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE, + manifest_hash VARCHAR(71) NOT NULL CHECK (manifest_hash ~ '^sha256:[0-9a-f]{64}$'), + publication_version_state_epoch BIGINT NOT NULL CHECK (publication_version_state_epoch > 0), + policy_count INTEGER NOT NULL CHECK (policy_count BETWEEN 1 AND 128), + policy_set_digest VARCHAR(71) NOT NULL CHECK (policy_set_digest ~ '^sha256:[0-9a-f]{64}$'), + sealed BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_realm_policy_capture (canonical_tenant_id, canonical_version_id) +); + +CREATE TABLE game_design_published_realm_policy ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + ordinal INTEGER NOT NULL CHECK (ordinal BETWEEN 0 AND 127), + realm_policy_id UUID NOT NULL UNIQUE, + source_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + logical_revision_id VARCHAR(128) NOT NULL CHECK (char_length(logical_revision_id) BETWEEN 1 AND 128), + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + policy_json TEXT NOT NULL CHECK (char_length(policy_json) BETWEEN 2 AND 4096), + policy_digest VARCHAR(71) NOT NULL CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$'), + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, realm_policy_id), + UNIQUE (canonical_tenant_id, canonical_version_id, ordinal), + UNIQUE (canonical_tenant_id, canonical_version_id, world_slug, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, source_revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_published_realm_policy_set (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_published_realm_policy_set() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; owner_game game%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; + capture game_design_realm_policy_capture%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + release published_release_bundle%ROWTYPE; + row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published realm policy set is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.sealed IS DISTINCT FROM FALSE OR NEW.sealed IS DISTINCT FROM TRUE + OR (to_jsonb(NEW) - 'sealed') IS DISTINCT FROM (to_jsonb(OLD) - 'sealed') THEN + RAISE EXCEPTION 'published realm policy set may only be sealed once' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF row_count <> NEW.policy_count + OR row_count <> jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') + OR realm_count <> row_count OR production_count <> 1 + OR NEW.policy_set_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy set is incomplete or has invalid cardinality' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.sealed IS DISTINCT FROM FALSE + OR jsonb_typeof(NEW.target_proof_json::JSONB) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + SELECT count(*) INTO target_proof_key_count + FROM jsonb_object_keys(NEW.target_proof_json::JSONB); + IF target_proof_key_count <> 7 + OR (NEW.target_proof_json::JSONB - ARRAY['canonicalTenantId', 'canonicalVersionId', 'gameDesignVersionRowId', + 'gameDesignVersionTenantKey', 'sourceGameRowId', 'sourceGameTenantKey', 'sourceProvenanceKind']) + IS DISTINCT FROM '{}'::JSONB + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalVersionId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceProvenanceKind') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO owner_version 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.target_proof_json::JSONB->>'gameDesignVersionTenantKey' + 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::TEXT = NEW.target_proof_json::JSONB->>'sourceGameRowId' + AND v.identity_source_game_tenant_key = NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + AND v.identity_source_provenance_kind = NEW.target_proof_json::JSONB->>'sourceProvenanceKind'; + IF NOT FOUND OR owner_version.id IS DISTINCT FROM NEW.game_design_version_row_id + OR owner_version.version_state IS DISTINCT FROM 'PUBLISHED' + OR owner_version.version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR owner_version.version_number IS DISTINCT FROM NEW.version_number + OR owner_version.is_script_only IS DISTINCT FROM FALSE + OR owner_version.script_patch_version IS NOT NULL + OR owner_version.base_version_id IS NOT NULL + OR NEW.target_proof_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR NEW.target_proof_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.target_proof_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.target_proof_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.target_proof_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'published realm policy set differs from exact full Version owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT g.* INTO STRICT owner_game FROM game g WHERE g.id = owner_version.identity_source_game_row_id; + IF owner_game.id::TEXT IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameRowId' + OR owner_game.tenant_id IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + OR owner_game.tenant_identity_provenance_kind IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceProvenanceKind' + OR owner_game.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id THEN + RAISE EXCEPTION 'published realm policy set source provenance changed' USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set operation is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO capture FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set source capture is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT * INTO release FROM published_release_bundle + WHERE tenant_id = owner_version.tenant_id AND version_id = owner_version.id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set release bundle is unavailable' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome IS DISTINCT FROM 'PUBLISHED' + OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.terminal_evidence_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR operation.release_content_bytes IS DISTINCT FROM NEW.release_content_bytes + OR operation.published_release_bundle_digest IS DISTINCT FROM NEW.published_release_bundle_digest + OR operation.publication_version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR operation.tenant_id IS DISTINCT FROM owner_version.tenant_id + OR operation.version_id IS DISTINCT FROM owner_version.id + OR operation.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR capture.commit_id IS DISTINCT FROM NEW.source_commit_id + OR snapshot.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR publication_release_content(release) IS DISTINCT FROM NEW.release_content_bytes + OR 'sha256:' || encode(sha256(publication_release_content(release)), 'hex') + IS DISTINCT FROM NEW.published_release_bundle_digest + OR release.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR release.version_number IS DISTINCT FROM NEW.version_number + OR release.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR release.manifest_hash IS DISTINCT FROM NEW.manifest_hash + OR to_jsonb(release)::TEXT IS DISTINCT FROM operation.release_row_json + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.visible_commit_id = NEW.source_commit_id AND s.source_epoch = NEW.source_epoch) + OR 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.commit_id = NEW.source_commit_id) + OR jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') <> NEW.policy_count THEN + RAISE EXCEPTION 'published realm policy set is not bound to exact sealed operation, capture, source, and release' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy_set FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_set(); + +CREATE FUNCTION guard_published_realm_policy_row() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + matching JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'published realm policy rows are immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND OR set_row.sealed THEN + RAISE EXCEPTION 'published realm policy row requires its open atomic set' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = set_row.source_commit_id; + SELECT p INTO matching FROM jsonb_array_elements(snapshot.snapshot_json::JSONB->'policies') + WITH ORDINALITY AS entries(p, source_ordinal) + WHERE source_ordinal = NEW.ordinal + 1 + AND p->>'commitId' = NEW.source_commit_id::TEXT + AND p->>'revisionId' = NEW.source_revision_id::TEXT + AND p->>'logicalRevisionId' = NEW.logical_revision_id + AND p->'policy' = NEW.policy_json::JSONB; + IF matching IS NULL + OR NEW.world_slug IS DISTINCT FROM matching->'policy'->>'worldSlug' + OR NEW.realm_slug IS DISTINCT FROM matching->'policy'->>'realmSlug' + OR NEW.visible IS DISTINCT FROM (matching->'policy'->>'visible')::BOOLEAN + OR NEW.public_production IS DISTINCT FROM (matching->'policy'->>'publicProduction')::BOOLEAN + OR jsonb_typeof(NEW.policy_json::JSONB) IS DISTINCT FROM 'object' + OR NEW.policy_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy row differs from exact captured source revision' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_row_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_row(); + +CREATE FUNCTION verify_published_realm_policy_set_commit() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; row_count BIGINT; + realm_count BIGINT; production_count BIGINT; +BEGIN + SELECT * INTO STRICT set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT set_row.sealed OR row_count <> set_row.policy_count OR realm_count <> row_count + OR production_count <> 1 OR row_count NOT BETWEEN 1 AND 128 THEN + RAISE EXCEPTION 'published realm policy set did not commit as one complete canonical set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER published_realm_policy_set_commit_guard + AFTER INSERT OR UPDATE ON game_design_published_realm_policy_set + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_published_realm_policy_set_commit(); + +CREATE FUNCTION deny_published_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'published realm policy evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy_set FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +CREATE TRIGGER published_realm_policy_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java new file mode 100644 index 0000000000..f67705e9f7 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -0,0 +1,336 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +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.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; + +/** + * ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. + */ +public final class IsolatedPublicationOwnerSetup { + private IsolatedPublicationOwnerSetup() {} + + /** Fixture-only visibility advance; supplied owner authority remains explicitly isolated. */ + public static void advanceIsolatedVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + + /** Actual joined source captures; supplied remote owner authority remains explicitly isolated. */ + public static void advanceIsolatedSourceVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceSourceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + + /** + * Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. + */ + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED owner transaction proof"); + } + + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, false); + } + + /** Actual source inheritance precedes selection; only the remote owner inputs are isolated. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED remote owner transaction proof", true); + } + + /** Actual source inheritance precedes selection; this does not freeze selected source. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, true); + } + + /** Resolve and retain the exact current authored or genesis source base for this fixture. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + String sourceBaseReference) + throws Exception { + return retain( + dsl, + target, + draftEpoch, + notes, + true, + Objects.requireNonNull(sourceBaseReference, "sourceBaseReference")); + } + + /** + * Finalizer-only fixture: author a complete minimal policy, select a later World-only commit, and + * freeze both exact selected source captures in the caller-owned owner transaction. + */ + public static GameDesignPublicationOperation retainFrozenSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target); + GameDesignPublicationOperation operation = + retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit); + new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation); + return operation; + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources) + throws Exception { + return retain(dsl, target, draftEpoch, notes, captureSources, null); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + String sourceBaseReference) + throws Exception { + var sources = new GameDesignSourceRepository(dsl); + var reviewed = new GameDesignReviewedBaseRepository(dsl); + var evidence = + captureSources + ? reviewed.resolve( + target, + DraftBaseReference.parse( + sourceBaseReference == null + ? "genesis:" + + sources.readGenesis(target).orElseThrow().policy().receiptId() + : sourceBaseReference)) + : null; + var seed = + captureSources + ? IsolatedPublicationOperationFixtures.fresh( + target, evidence.reference().canonicalValue()) + : IsolatedPublicationOperationFixtures.fresh(target); + var draft = seed.account().input().selection().selectedCommit(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + // The original Draft Account/World result is stipulated upstream fixture evidence, not a new + // GD Draft-authorization operation or live Account authority issued by this helper. + if (captureSources) { + sources.claimReviewed(draft, evidence); + } else { + coordinator.claim(draft); + } + coordinator.claimApplicationSlot(draft); + var epochs = + draft.affectedUnits().stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + draft.commitId(), + draft.digest(), + "ISOLATED-world-applied", + seed.world().appliedResultBytes(), + epochs); + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(draft, outcome); + var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome)); + if (captureSources) { + coordinator.advanceSourceVisibilityFence(draft, proof); + } else { + coordinator.advanceVisibilityFence(draft, proof); + } + coordinator.releaseApplicationSlot(draft); + var selection = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), + Long.toString(draftEpoch), + notes, + draft.requestId(), + draft.commitId(), + draft.digest())) + .selection(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + seed.world()); + var attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + var versionRow = + dsl.fetchOne( + "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); + if (versionRow == null) { + throw new IllegalStateException("Selected authored Version row is absent"); + } + attempt.setVersionNumber(versionRow.get(0, Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(dsl).save(attempt); + GameDesignPublicationOperationRepository operations = + new GameDesignPublicationOperationRepository(dsl); + operations.reserve(operation); + return operation; + } + + private static String retainPublicProductionPolicy( + DSLContext dsl, DraftCommitBinding.TargetProof target) { + var sources = new GameDesignSourceRepository(dsl); + var genesis = sources.readGenesis(target).orElseThrow(); + String baseReference = "genesis:" + genesis.policy().receiptId(); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + baseReference, + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"," + + "\"logicalRevisionId\":\"isolated-finalizer-main\"," + + "\"policy\":{\"schemaVersion\":1,\"worldSlug\":\"world\"," + + "\"worldDisplayName\":\"World\",\"realmSlug\":\"main\"," + + "\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var reviewed = new GameDesignReviewedBaseRepository(dsl); + sources.claimReviewed( + binding, reviewed.resolve(target, DraftBaseReference.parse(baseReference))); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + coordinator.releaseApplicationSlot(binding); + return binding.commitId().toString(); + } + + /** Storage fixture commit only; does not substitute for actual command finalization proof. */ + public static PublishedReleaseBundle commitStorage( + DSLContext dsl, + VersionRepository versions, + GameDesignPublicationOperation operation, + Supplier releaseWrite) { + var attempts = new PublishAttemptRepository(dsl); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + attempts.requirePublishedOperation(attempt); + return releaseWrite.get(); + } + attempts.requirePublicationPending(attempt); + var version = + versions + .findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()) + .orElseThrow(); + var snapshot = + new VersionAssetPublicationRepository(dsl) + .freezeOrReadSnapshot(operation.tenantKey(), version.getVersionNumber()); + PublishedReleaseBundle bundle = releaseWrite.get(); + if (snapshot.versionId() != operation.versionId() + || !snapshot.items().isEmpty() + || bundle.getManifestSchemaVersion() == null + || bundle.getManifestSchemaVersion() != 1 + || !"[]".equals(bundle.getArtifactDigestsJson()) + || !"[]".equals(bundle.getRequiredManifestAssetKeysJson()) + || bundle.getManifestHash() == null + || !bundle.getManifestHash().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + "Isolated publication fixture requires the exact empty asset candidate for its Version"); + } + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); + versions.save(version); + var artifact = new VersionAssetArtifact(); + artifact.setTenantId(operation.tenantKey()); + artifact.setVersionId(operation.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(operation.workflowId()); + artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); + artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); + artifact.setExportedManifestAssetKeysJson(bundle.getRequiredManifestAssetKeysJson()); + String manifestDigest = bundle.getManifestHash(); + artifact.setPublishedObjectProofsJson( + "[{\"immutableObjectKey\":\"manifests/sha256/" + + manifestDigest.substring("sha256:".length()) + + "\",\"contentDigest\":\"" + + manifestDigest + + "\"}]"); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + artifact.setCandidatePublicBaseUrl("https://assets.example.invalid/assets"); + new VersionAssetArtifactRepository(dsl).save(artifact); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + attempts.sealPublication(attempt, true); + return bundle; + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java new file mode 100644 index 0000000000..9457f43972 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import tools.jackson.databind.ObjectMapper; + +/** + * ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. + */ +public final class IsolatedPublicationOperationFixtures { + private IsolatedPublicationOperationFixtures() {} + + /** + * A new fixture operation and freeze, never a reinterpretation of retained publication history. + */ + public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) + throws Exception { + var seed = PublishedWorldSelectorFixtures.evidence(target); + return fresh(target, seed); + } + + public static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, String baseReference) throws Exception { + return fresh(target, PublishedWorldSelectorFixtures.evidence(target, baseReference)); + } + + private static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence seed) + throws Exception { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), + originalDraftAccount.inputDigest()); + var appliedEpochs = + draft.affectedUnits().stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + String vector = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + List.of( + Map.of( + "owner", + "WORLD_MANAGEMENT", + "status", + "APPLIED", + "commitId", + draft.commitId().toString(), + "bindingDigest", + draft.digest(), + "resultIdentity", + "ISOLATED-world-applied", + "resultBytesBase64", + Base64.getEncoder().encodeToString(seed.appliedResultBytes()), + "appliedEpochs", + appliedEpochs)))), + StandardCharsets.UTF_8); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "ISOLATED-publication-request", + "5", + "ISOLATED owner transaction proof", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + vector, + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + return forSelection(selected, seed); + } + + public static GameDesignPublicationOperation forSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var target = selected.target(); + var intent = selected.intent(); + var draft = selected.selectedCommit(); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalDraftAccount.actorAccountId(), selected), + java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()) + .map( + kind -> + new DraftAuthorizationFenceBinding.SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> + originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> + originalDraftAccount.actorAccountId() + + "/" + + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, + "1", + "1", + null, + null, + ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))) + .toList()); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + seed.request().intakeRequestId(), + UUID.randomUUID(), + intent.publishRequestId(), + selected.digest().substring(7), + Long.parseLong(intent.expectedVersionStateEpoch()), + FiremudWorkflowIds.workflowId( + "publish", + target.canonicalTenantId().toString(), + "publish-request", + intent.publishRequestId()), + draft.commitId().toString(), + seed.request().contentDigest(), + 3, + seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperation(account, world); + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 0408bb88ed..277640b137 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -77,10 +78,7 @@ public static WorldPublishedStartLocationEvidence evidence( public static List participants(long versionId, WorldPublishedStartLocationEvidence evidence) { return participants( - versionId, - evidence, - net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .SCHEMA_VERSION); + versionId, evidence, AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION); } public static List @@ -106,8 +104,8 @@ public static WorldPublishedStartLocationEvidence evidence( "WORLD_MANAGEMENT".equals(owner) ? evidence.request().contentDigest() : "c".repeat(64), - net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .supportedParticipantDigestSchema(owner, attestationSchemaVersion), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, attestationSchemaVersion), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..d9094132da --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -0,0 +1,590 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.UUID; +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.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +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; + +/** Real local source writers and coordinator SQL; publication Account and World remain isolated. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); + assertThat(genesis.policy().creationTransactionId()) + .isEqualTo(genesis.command().creationTransactionId()); + assertThat(fixture.tx(() -> fixture.sources().enrollFreshDraft(fixture.target()))) + .isEqualTo(genesis); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + + DraftCommitBinding policy = + binding( + fixture.target(), "genesis:" + genesis.policy().receiptId(), "0", null, "main", true); + var policyResult = apply(fixture, policy); + synchronize(fixture, policy, policyResult); + var policySnapshot = + fixture.sources().readSynchronized(fixture.target(), policy.commitId()).orElseThrow(); + assertThat(policySnapshot.policy().policies()).hasSize(1); + assertThat(policySnapshot.command().definitions()).isEmpty(); + + DraftCommitBinding command = + binding(fixture.target(), policy.commitId().toString(), null, "0", null, false); + var commandResult = apply(fixture, command); + synchronize(fixture, command, commandResult); + var commandSnapshot = + fixture.sources().readSynchronized(fixture.target(), command.commitId()).orElseThrow(); + assertThat(commandSnapshot.policy().policies()) + .containsExactlyElementsOf(policySnapshot.policy().policies()); + assertThat(commandSnapshot.command().definitions()).hasSize(1); + assertThat(commandResult.ownerOutcome().appliedEpochs()) + .containsExactly(commandResult.command().orElseThrow().commandAppliedEpoch()); + + DraftCommitBinding mixed = + binding(fixture.target(), command.commitId().toString(), "1", "1", "main", true); + var mixedResult = apply(fixture, mixed); + assertThat(mixedResult.ownerOutcome().appliedEpochs()).hasSize(2); + assertThat(mixedResult.ownerOutcome().resultBytes()) + .contains(mixedResult.command().orElseThrow().canonicalBytes()); + assertThat(fixture.tx(() -> fixture.sources().apply(policy)).ownerOutcome()) + .isEqualTo(policyResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(command)).ownerOutcome()) + .isEqualTo(commandResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(mixed)).ownerOutcome()) + .isEqualTo(mixedResult.ownerOutcome()); + synchronize(fixture, mixed, mixedResult); + var mixedSnapshot = + fixture.sources().readSynchronized(fixture.target(), mixed.commitId()).orElseThrow(); + assertThat(mixedSnapshot.policy().sourceEpoch()).isEqualTo("2"); + assertThat(mixedSnapshot.command().sourceEpoch()).isEqualTo("2"); + assertThat(mixedSnapshot.command().definitions().getFirst().sourceCommitId()) + .isEqualTo(mixed.commitId()); + assertThat(fixture.tx(() -> fixture.sources().captureSynchronized(mixed))) + .isEqualTo(mixedSnapshot); + assertThat(fixture.tx(() -> fixture.sources().apply(policy)).ownerOutcome()) + .isEqualTo(policyResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(command)).ownerOutcome()) + .isEqualTo(commandResult.ownerOutcome()); + } + + @Test + void requiredOwnerSetMustBeNonEmptyDistinctAndKnownBeforeAnyOwnerFence() { + Fixture fixture = fixture(); + String base = + "genesis:" + + fixture.sources().readGenesis(fixture.target()).orElseThrow().policy().receiptId(); + String[] invalidRequiredOwnerJson = { + null, + "[]", + "\"GAME_DESIGN_CONTROL_PLANE\"", + "[\"GAME_DESIGN_CONTROL_PLANE\",1]", + "[\"UNKNOWN_OWNER\"]", + "[\"GAME_DESIGN_CONTROL_PLANE\",\"GAME_DESIGN_CONTROL_PLANE\"]" + }; + + for (String requiredOwnerJson : invalidRequiredOwnerJson) { + DraftCommitBinding binding = binding(fixture.target(), base, "0", null, "main", true); + assertThat(binding.requiredOwners()).containsExactly(Owner.GAME_DESIGN_CONTROL_PLANE); + String rawBindingJson = withRawRequiredOwners(binding.canonicalJson(), requiredOwnerJson); + + assertThatThrownBy(() -> insertRawDraftCommit(fixture, binding, rawBindingJson)) + .hasMessageContaining( + "Draft commit requiredOwners must be a non-empty array of distinct known owner strings"); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())).isEmpty(); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_draft_commit"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_draft_commit_owner_result"))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_draft_commit_visibility_fence"))) + .isZero(); + } + } + + @Test + void sourceApplicationsRequireReservedReviewedBaseBeforeEitherOwnerCanWrite() { + Fixture policyFixture = fixture(); + UUID policyGenesis = + policyFixture + .sources() + .readGenesis(policyFixture.target()) + .orElseThrow() + .policy() + .receiptId(); + DraftCommitBinding policy = + binding(policyFixture.target(), "genesis:" + policyGenesis, "0", null, "main", true); + assertMissingReviewedBaseDeniesOwnerApply( + policyFixture, + policy, + () -> new RealmPolicySourceRepository(policyFixture.dsl()).apply(policy)); + var policyResult = apply(policyFixture, policy); + synchronize(policyFixture, policy, policyResult); + assertThat(policyFixture.tx(() -> policyFixture.sources().apply(policy)).ownerOutcome()) + .isEqualTo(policyResult.ownerOutcome()); + + Fixture commandFixture = fixture(); + UUID commandGenesis = + commandFixture + .sources() + .readGenesis(commandFixture.target()) + .orElseThrow() + .command() + .receiptId(); + DraftCommitBinding command = + binding(commandFixture.target(), "genesis:" + commandGenesis, null, "0", null, false); + assertMissingReviewedBaseDeniesOwnerApply( + commandFixture, + command, + () -> new CommandSourceRepository(commandFixture.dsl()).apply(command)); + var commandResult = apply(commandFixture, command); + synchronize(commandFixture, command, commandResult); + assertThat(commandFixture.tx(() -> commandFixture.sources().apply(command)).ownerOutcome()) + .isEqualTo(commandResult.ownerOutcome()); + } + + private static void assertMissingReviewedBaseDeniesOwnerApply( + Fixture fixture, DraftCommitBinding binding, Runnable ownerApply) { + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture + .coordinator() + .markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + ownerApply.run(); + return null; + })) + .hasMessageContaining("Draft source application requires exact reviewed base evidence"); + + assertThat(fixture.sources().readGenesis(fixture.target())).contains(genesis); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())).isEmpty(); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_command_source_application"))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_reviewed_draft_base"))).isZero(); + } + + @Test + void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { + Fixture fixture = fixture(); + DraftCommitBinding incomplete = + binding( + fixture.target(), + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId(), + "0", + null, + "private", + false); + start(fixture, incomplete); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.sources().apply(incomplete); + status.setRollbackOnly(); + }); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) + .isZero(); + assertThat( + fixture + .coordinator() + .read(fixture.target(), incomplete.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome()) + .isEmpty(); + var result = fixture.tx(() -> fixture.sources().apply(incomplete)); + synchronize(fixture, incomplete, result); + + var unsupported = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + incomplete.commitId().toString(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("unused"))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "1"))); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().apply(unsupported))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete supported Game Design source scopes"); + + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET)); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + } + + @Test + void emptyRealmPolicySourceFailsWithTypedPublicationGateBeforeCapture() { + Fixture fixture = fixture(); + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET)); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + } + + @Test + void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { + Fixture fixture = fixture(); + var authored = + binding( + fixture.target(), + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId(), + "0", + "0", + "main", + true); + synchronize(fixture, authored, apply(fixture, authored)); + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.sources().freeze(operation); + status.setRollbackOnly(); + }); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + var first = fixture.tx(() -> fixture.sources().freeze(operation)); + var retry = fixture.tx(() -> fixture.sources().freeze(operation)); + var read = fixture.sources().readCapture(operation).orElseThrow(); + assertThat(retry.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); + assertThat(retry.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(read.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); + assertThat(read.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(read.command().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(read.policy().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + } + + private static GameDesignSourceRepository.Application apply( + Fixture fixture, DraftCommitBinding binding) { + start(fixture, binding); + return fixture.tx(() -> fixture.sources().apply(binding)); + } + + private static void start(Fixture fixture, DraftCommitBinding binding) { + fixture.tx( + () -> { + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + fixture + .sources() + .claimReviewed( + binding, + reviewed.resolve( + fixture.target(), + net.firedevops.firemud.common.authoring.DraftBaseReference.parse( + binding.baseCommitId()))); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); + } + + private static void synchronize( + Fixture fixture, DraftCommitBinding binding, GameDesignSourceRepository.Application result) { + fixture.tx( + () -> { + fixture + .coordinator() + .advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(result.ownerOutcome()))); + fixture.sources().captureSynchronized(binding); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + } + + private static DraftCommitBinding binding( + TargetProof target, + String base, + String policyEpoch, + String commandEpoch, + String realm, + boolean production) { + var revisions = new java.util.ArrayList(); + var scopes = new java.util.ArrayList(); + if (commandEpoch != null) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload(command("look", realm == null ? "see" : realm)))); + scopes.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + target.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + commandEpoch)); + } + if (policyEpoch != null) { + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-" + + realm + + "\",\"policy\":{\"schemaVersion\":1,\"worldSlug\":\"world\"," + + "\"worldDisplayName\":\"World\",\"realmSlug\":\"" + + realm + + "\"," + + "\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}}"; + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)); + scopes.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + policyEpoch)); + } + return DraftCommitBinding.create( + target, UUID.randomUUID(), UUID.randomUUID(), base, revisions, scopes); + } + + private static String withRawRequiredOwners(String canonicalJson, String requiredOwnerJson) { + String validRequiredOwners = "\"requiredOwners\":[\"GAME_DESIGN_CONTROL_PLANE\"]"; + assertThat(canonicalJson).contains(validRequiredOwners); + if (requiredOwnerJson == null) { + return canonicalJson.replace(validRequiredOwners + ",", ""); + } + return canonicalJson.replace(validRequiredOwners, "\"requiredOwners\":" + requiredOwnerJson); + } + + private static void insertRawDraftCommit( + Fixture fixture, DraftCommitBinding binding, String rawBindingJson) { + TargetProof target = binding.target(); + 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 + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + rawBindingJson); + } + + private static String command(String id, String alias) { + return "{\"schemaVersion\":1,\"commandId\":\"" + + id + + "\",\"semanticOwner\":\"WORLD\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"" + + alias + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," + + "\"legacyExtension\":{\"kept\":true}}"; + } + + private static Fixture fixture() { + String schema = "gd_combined_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var properties = new PostgresProperties(); + properties.setSchema(schema); + TargetProof target = + write.execute( + status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED composed source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + }); + return new Fixture( + dsl, + write, + target, + new GameDesignSourceRepository(dsl), + new DraftCommitCoordinatorRepository(dsl)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + TargetProof target, + GameDesignSourceRepository sources, + DraftCommitCoordinatorRepository coordinator) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..5280ade5c9 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -0,0 +1,1252 @@ +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.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.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyApplication; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySnapshot; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceService; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +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; +import tools.jackson.databind.ObjectMapper; + +/** Real Game Design source writes; remote Account and World authority remain ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class RealmPolicySourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { + var fixture = freshFixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); + assertThat(genesis.policy().creationTransactionId()) + .isEqualTo(genesis.command().creationTransactionId()); + assertThat(fixture.reads().readGenesis(fixture.target())).contains(genesis.policy()); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_snapshot"))).isZero(); + var first = policyBinding(fixture, "main", true); + start(fixture, first); + var applied = fixture.tx(() -> fixture.sources().apply(first).policy().orElseThrow()); + assertThat(applied.genesis()).isEqualTo(genesis.policy()); + assertThat(applied.inheritedCommitId()).isNull(); + assertThat(applied.snapshot().sourceEpoch()).isEqualTo("1"); + assertThat( + fixture.tx( + () -> fixture.sources().apply(first).policy().orElseThrow().canonicalBytes())) + .containsExactly(applied.canonicalBytes()); + synchronize(fixture, first, applied); + assertThat(fixture.reads().readSnapshot(fixture.target(), first.commitId()).orElseThrow()) + .isEqualTo(applied.snapshot()); + } + + @Test + void incompleteDraftPoliciesCanSynchronizeButCannotBecomePublicationCapture() { + var fixture = freshFixture(); + var first = policyBinding(fixture, "private", false); + start(fixture, first); + var applied = fixture.tx(() -> fixture.sources().apply(first).policy().orElseThrow()); + synchronize(fixture, first, applied); + var operation = publication(fixture); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().freeze(operation))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exactly one visible"); + assertThat(fixture.reads().readCapture(operation)).isEmpty(); + } + + @Test + void explicitDeleteMovesRealmAndRetainsDeleteIdentityInTheCompleteStoredBinding() { + var fixture = policyFixture(); + var side = policyBinding(fixture, "side", false); + start(fixture, side); + var sideResult = fixture.tx(() -> fixture.sources().apply(side).policy().orElseThrow()); + synchronize(fixture, side, sideResult); + + UUID deleteRevisionId = UUID.randomUUID(); + var move = + policyMutationBinding( + fixture, + List.of( + policyDeleteRevision("0", deleteRevisionId, "authored-main", "world", "main"), + policyUpsertRevision( + "1", UUID.randomUUID(), "authored-main", "new-world", "main", true))); + start(fixture, move); + var applied = fixture.tx(() -> fixture.sources().apply(move).policy().orElseThrow()); + assertThat(applied.snapshot().sourceEpoch()).isEqualTo("3"); + assertThat(applied.snapshot().policies()) + .extracting(policy -> policy.policy().worldSlug() + "/" + policy.policy().realmSlug()) + .containsExactly("new-world/main", "world/side"); + assertThat( + fixture.tx(() -> fixture.sources().apply(move).policy().orElseThrow().canonicalBytes())) + .containsExactly(applied.canonicalBytes()); + + var stored = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT c.binding_json, a.request_id, a.snapshot_json " + + "FROM game_design_draft_commit c " + + "JOIN game_design_realm_policy_application a " + + "ON a.canonical_tenant_id = c.canonical_tenant_id " + + "AND a.canonical_version_id = c.canonical_version_id " + + "AND a.request_id = c.request_id AND a.commit_id = c.commit_id " + + "WHERE c.canonical_tenant_id = ? AND c.canonical_version_id = ? AND c.commit_id = ?", + move.target().canonicalTenantId(), + move.target().canonicalVersionId(), + move.commitId()), + "explicit deletion must retain its complete synchronized owner binding"); + assertThat(stored.get("binding_json", String.class)).isEqualTo(move.canonicalJson()); + assertThat(stored.get("request_id", UUID.class)).isEqualTo(move.requestId()); + assertThat(stored.get("snapshot_json", String.class)) + .isEqualTo(applied.snapshot().canonicalJson()); + + synchronize(fixture, move, applied); + var reusedDeleteIdentity = + policyMutationBinding( + fixture, + List.of( + policyUpsertRevision( + "0", + deleteRevisionId, + "authored-reused-delete", + "other-world", + "other", + false))); + start(fixture, reusedDeleteIdentity); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(reusedDeleteIdentity))) + .hasMessageContaining("Authored policy revision identity cannot be reused"); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT source_epoch FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "retained policy source head must remain present after rejected reuse") + .get(0, String.class)) + .isEqualTo("3"); + } + + @Test + void explicitDeleteRejectsAnAbsentSelectorWithoutAdvancingThePolicySource() { + var fixture = policyFixture(); + var missingDelete = + policyMutationBinding( + fixture, + List.of( + policyDeleteRevision( + "0", UUID.randomUUID(), "authored-delete-missing", "world", "missing"))); + start(fixture, missingDelete); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(missingDelete))) + .hasMessageContaining("Cannot delete an absent policy selector"); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne("SELECT source_epoch FROM game_design_realm_policy_source"), + "retained policy source head must remain present after absent deletion") + .get(0, String.class)) + .isEqualTo("1"); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) + .isEqualTo(1); + } + + @Test + void retainedVersionUpdateIsNotFreshGenesisAndActualCreationRollbackLeavesNoReceipt() { + var fixture = retainedFixture(); + migrateLatest(fixture); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "UPDATE version SET notes = 'ISOLATED retained update' WHERE id = ?", + fixture.target().gameDesignVersionRowId()); + return fixture.policies().recordFreshGenesis(fixture.target()); + })) + .hasMessageContaining("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); + var rolledBack = new java.util.concurrent.atomic.AtomicReference(); + fixture + .write() + .executeWithoutResult( + status -> { + var properties = new PostgresProperties(); + var version = new Version(); + version.setTenantId(fixture.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + version = new VersionRepository(fixture.dsl()).save(version); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + rolledBack.set(target); + RealmPolicyGenesis receipt = fixture.policies().recordFreshGenesis(target); + assertThat(fixture.policies().recordFreshGenesis(target)).isEqualTo(receipt); + status.setRollbackOnly(); + }); + assertThat(fixture.reads().readGenesis(rolledBack.get())).isEmpty(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT id FROM version WHERE id = ?", + rolledBack.get().gameDesignVersionRowId())) + .isNull(); + } + + @Test + void sourceComposesOneOwnerResultAndCommandOnlyFenceInheritsPolicy() { + var fixture = freshFixture(); + var policy = policyBinding(fixture, "main", true); + var commandRevision = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"ISOLATED-command\"," + + "\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," + + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}")); + var commandScope = + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "0"); + var mixed = + DraftCommitBinding.create( + policy.target(), + policy.requestId(), + policy.commitId(), + policy.baseCommitId(), + List.of(policy.revisions().getFirst(), commandRevision), + List.of(commandScope, policy.affectedUnits().getFirst())); + start(fixture, mixed); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(mixed))) + .hasMessageContaining("Mixed Game Design commit"); + var mixedApplication = fixture.tx(() -> fixture.sources().apply(mixed)); + assertThat(mixedApplication.command()).isPresent(); + assertThat(mixedApplication.policy()).isPresent(); + assertThat(mixedApplication.ownerOutcome().resultBytes()) + .contains(mixedApplication.command().orElseThrow().canonicalBytes()); + synchronize(fixture, mixed, mixedApplication); + var prior = fixture.reads().readSnapshot(fixture.target(), mixed.commitId()).orElseThrow(); + var commandOnly = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + mixed.commitId().toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + commandRevision.payload())), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "1"))); + start(fixture, commandOnly); + var commandApplication = fixture.tx(() -> fixture.sources().apply(commandOnly)); + assertThat(commandApplication.command()).isPresent(); + assertThat(commandApplication.policy()).isEmpty(); + synchronize(fixture, commandOnly, commandApplication); + var inherited = + fixture + .sources() + .readSynchronized(fixture.target(), commandOnly.commitId()) + .orElseThrow() + .policy(); + assertThat(inherited.sourceEpoch()).isEqualTo(prior.sourceEpoch()); + assertThat(inherited.policies()).containsExactlyElementsOf(prior.policies()); + } + + @Test + void sourceHeadRejectsUnprovenTransitionsAndDisjointCaptureInheritsExactPredecessor() { + var fixture = freshFixture(); + var first = policyBinding(fixture, "main", true); + start(fixture, first); + var firstApplication = fixture.tx(() -> fixture.sources().apply(first).policy().orElseThrow()); + synchronize(fixture, first, firstApplication); + + var second = policyBinding(fixture, "private", false); + start(fixture, second); + var secondApplication = + fixture.tx(() -> fixture.sources().apply(second).policy().orElseThrow()); + synchronize(fixture, second, secondApplication); + var current = fixture.reads().readSnapshot(fixture.target(), second.commitId()).orElseThrow(); + assertThat(current.policies()).hasSize(2); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1', visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '4' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source pointer must advance to its exact current synchronized snapshot"); + + var disjoint = commandOnlyBinding(fixture, second.commitId(), "0"); + start(fixture, disjoint); + var disjointApplication = fixture.tx(() -> fixture.sources().apply(disjoint)); + synchronize(fixture, disjoint, disjointApplication); + var inherited = + fixture + .sources() + .readSynchronized(fixture.target(), disjoint.commitId()) + .orElseThrow() + .policy(); + assertThat(inherited.sourceEpoch()).isEqualTo(current.sourceEpoch()); + assertThat(inherited.policies()).containsExactlyElementsOf(current.policies()); + var snapshotRow = + fixture + .dsl() + .fetchOne( + "SELECT inherited_commit_id FROM game_design_realm_policy_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + disjoint.commitId()); + assertThat(snapshotRow).isNotNull(); + assertThat(snapshotRow.get("inherited_commit_id", UUID.class)).isEqualTo(second.commitId()); + } + + @Test + void retainedHistoricalSourceHeadInsertRequiresItsVisibleSnapshotEpoch() { + var fixture = retainedFixture(); + // Preserve the legacy row set at V50.13, then carry it through the current migrations. + var snapshot = seedRetainedSnapshot(fixture, "1"); + migrateLatest(fixture); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '2', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()))) + .hasMessageContaining("realm policy source head must match its visible snapshot epoch"); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_source"))).isZero(); + assertThat( + fixture + .reads() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow()) + .isEqualTo(snapshot); + + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()); + return null; + }); + var sourceHead = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT source_epoch FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "valid source-head insert should persist a row"); + assertThat(sourceHead.get("source_epoch", String.class)).isEqualTo("1"); + assertThat(fixture.reads().readSnapshot(fixture.target(), fixture.baseline().commitId())) + .contains(snapshot); + } + + @Test + void visibilityPointerCannotRewindDeleteOrTruncateAndExactFenceRetryRemainsStable() { + var fixture = freshFixture(); + var first = policyBinding(fixture, "main", true); + start(fixture, first); + var firstApplication = fixture.tx(() -> fixture.sources().apply(first).policy().orElseThrow()); + synchronize(fixture, first, firstApplication); + + var second = policyBinding(fixture, "private", false); + start(fixture, second); + var secondApplication = + fixture.tx(() -> fixture.sources().apply(second).policy().orElseThrow()); + synchronize(fixture, second, secondApplication); + + var replayedFence = + fixture.tx( + () -> + fixture + .coordinator() + .advanceSourceVisibilityFence( + second, + new DraftCommitCoordinatorRepository.CoordinatorProof( + second, List.of(secondApplication.ownerOutcome())))); + assertThat(replayedFence.commitId()).isEqualTo(second.commitId()); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_draft_commit_visibility SET request_id = ?, commit_id = ?, input_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.requestId(), + first.commitId(), + first.digest(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining("may advance only to its actively applying commit"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining("Draft visibility pointers cannot be deleted"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> fixture.dsl().execute("TRUNCATE game_design_draft_commit_visibility"))) + .hasMessageContaining("Draft visibility pointers cannot be truncated"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + } + + @Test + void absentBaselineDeniesAndApplicationReplayAndMismatchBindActualCoordinatorResult() { + var fixture = retainedFixture(); + migrateLatest(fixture); + var binding = historicalPolicyBinding(fixture.target(), "0", "main", true); + startUnreviewed(fixture, binding); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(binding))) + .hasMessageContaining("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + var real = policyFixture(); + var mutation = policyBinding(real, "private", false); + start(real, mutation); + var result = real.tx(() -> real.sources().apply(mutation).policy().orElseThrow()); + assertThat( + real.tx(() -> real.sources().apply(mutation).policy().orElseThrow().canonicalBytes())) + .containsExactly(result.canonicalBytes()); + var changed = + DraftCommitBinding.create( + mutation.target(), + mutation.requestId(), + mutation.commitId(), + mutation.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + mutation.revisions().getFirst().revisionId(), + Owner.GAME_DESIGN_CONTROL_PLANE, + mutation.revisions().getFirst().payload().replace("private", "changed"))), + mutation.affectedUnits()); + assertThatThrownBy(() -> real.tx(() -> real.policies().apply(changed))) + .hasMessageContaining("POLICY_COMMIT_BINDING_CONFLICT"); + assertThat( + real.coordinator() + .read(real.target(), mutation.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome()) + .contains(result.ownerOutcome()); + } + + @Test + void rollbackAndPartialWritesPreserveLastVisibleSourceThenDisjointCommitInheritsExactProvenance() + throws Exception { + var fixture = policyFixture(); + var mutation = policyBinding(fixture, "private", false); + start(fixture, mutation); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.policies().apply(mutation); + status.setRollbackOnly(); + }); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table("game_design_realm_policy_application"), + DSL.field("commit_id").eq(mutation.commitId()))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))).isOne(); + var result = fixture.tx(() -> fixture.policies().apply(mutation)); + assertThat( + fixture + .reads() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow() + .policies()) + .hasSize(1); + assertThat(fixture.reads().readSnapshot(fixture.target(), mutation.commitId())).isEmpty(); + synchronize(fixture, mutation, result); + var operation = publication(fixture); + var inherited = + fixture + .reads() + .readSnapshot( + fixture.target(), + operation.account().input().selection().selectedCommit().commitId()) + .orElseThrow(); + assertThat(inherited.policies()).containsExactlyElementsOf(result.snapshot().policies()); + var capture = fixture.tx(() -> fixture.policies().freeze(operation)); + assertThat(fixture.tx(() -> fixture.policies().freeze(operation)).canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + assertThat(fixture.reads().readCapture(operation).orElseThrow().canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT outcome FROM game_design_publication_operation WHERE publish_workflow_id = ?", + operation.workflowId()), + "reserved publication fixture must have its persisted operation row") + .get(0, String.class)) + .isEqualTo("PENDING"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_snapshot SET snapshot_json = snapshot_json"))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("realm policy history is immutable"); + } + + @Test + void freezeAndSourceWriterUseSameVersionLockAndRollbackDoesNotLeaveCapture() throws Exception { + var fixture = policyFixture(); + var operation = publication(fixture); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.policies().freeze(operation); + status.setRollbackOnly(); + }); + assertThat(fixture.reads().readCapture(operation)).isEmpty(); + var frozen = new CountDownLatch(1); + var release = new CountDownLatch(1); + var attempting = new CountDownLatch(1); + var freezerPid = new java.util.concurrent.atomic.AtomicInteger(); + var writerPid = new java.util.concurrent.atomic.AtomicInteger(); + try (var executor = Executors.newFixedThreadPool(2)) { + var freezer = + executor.submit( + () -> + fixture.tx( + () -> { + var result = fixture.policies().freeze(operation); + freezerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "freezer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + frozen.countDown(); + await(release); + return result; + })); + assertThat(frozen.await(10, TimeUnit.SECONDS)).isTrue(); + var writer = + executor.submit( + () -> + fixture.tx( + () -> { + writerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "writer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + // Acquire the exact Version lock used by the repository's source writer + // before exercising the storage guard, independently of creator preflight. + fixture + .dsl() + .fetchOne( + "SELECT id FROM version WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '2' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + })); + assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); + boolean observedVersionBlock = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var activity = + fixture + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' " + + "AND query LIKE 'SELECT id FROM version%FOR UPDATE%' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + freezerPid.get(), writerPid.get()); + if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { + observedVersionBlock = true; + break; + } + Thread.sleep(25); + } + assertThat(observedVersionBlock) + .as("writer backend blocked by freezer on the exact Version SELECT FOR UPDATE") + .isTrue(); + release.countDown(); + assertThat(freezer.get(10, TimeUnit.SECONDS).snapshot().policies()).hasSize(1); + assertThatThrownBy(() -> writer.get(10, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .rootCause() + .hasMessageContaining("realm policy source is frozen"); + } finally { + release.countDown(); + } + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne("SELECT source_epoch FROM game_design_realm_policy_source"), + "retained Version fixture must have its realm-policy source row") + .get(0, String.class)) + .isEqualTo("1"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("ISOLATED fixture latch timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private static void start(Fixture fixture, DraftCommitBinding binding) { + fixture.tx( + () -> { + var reviewed = + new GameDesignReviewedBaseRepository(fixture.dsl()) + .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); + fixture.sources().claimReviewed(binding, reviewed); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); + } + + private static void startUnreviewed(Fixture fixture, DraftCommitBinding binding) { + fixture.tx( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); + } + + private static void synchronize( + Fixture fixture, DraftCommitBinding binding, RealmPolicyApplication result) { + synchronize(fixture, binding, result.ownerOutcome()); + } + + private static void synchronize( + Fixture fixture, DraftCommitBinding binding, GameDesignSourceRepository.Application result) { + synchronize(fixture, binding, result.ownerOutcome()); + } + + private static void synchronize( + Fixture fixture, + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.OwnerOutcome outcome) { + fixture.tx( + () -> { + fixture + .coordinator() + .advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + } + + private static GameDesignPublicationOperation publication(Fixture fixture) { + return fixture.tx( + () -> { + try { + // Existing fixture stipulates actual World and Account producer bytes; it runs GD's + // real + // disjoint World commit, selection, attempt and operation repositories. Capture + // integration + // here is isolated in the same transaction, not a claim of normal producer composition. + var operation = + IsolatedPublicationOwnerSetup.retain(fixture.dsl(), fixture.target(), 1); + fixture + .policies() + .captureSynchronized(operation.account().input().selection().selectedCommit()); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private static DraftCommitBinding policyBinding( + Fixture fixture, String realm, boolean production) { + TargetProof target = fixture.target(); + SourceHead head = currentSourceHead(fixture); + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-" + + realm + + "\",\"policy\":" + + policy.canonicalJson() + + "}"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + head.baseReference(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + head.sourceEpoch()))); + } + + private static DraftCommitBinding policyMutationBinding( + Fixture fixture, List revisions) { + TargetProof target = fixture.target(); + SourceHead head = currentSourceHead(fixture); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + head.baseReference(), + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + head.sourceEpoch()))); + } + + private static DraftCommitBinding historicalPolicyBinding( + TargetProof target, String epoch, String realm, boolean production) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-" + + realm + + "\",\"policy\":" + + policy.canonicalJson() + + "}"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-explicit-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + epoch))); + } + + private static SourceHead currentSourceHead(Fixture fixture) { + var row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT source_epoch, visible_commit_id, genesis_receipt_id " + + "FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "fresh Draft fixture must retain its actual policy source head"); + UUID visibleCommit = row.get("visible_commit_id", UUID.class); + UUID genesisReceipt = row.get("genesis_receipt_id", UUID.class); + UUID sharedGenesisReceipt = + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow( + () -> new IllegalStateException("fresh Draft fixture lacks shared genesis")) + .policy() + .receiptId(); + if (visibleCommit == null && !sharedGenesisReceipt.equals(genesisReceipt)) { + throw new IllegalStateException("empty source head differs from the shared genesis receipt"); + } + String baseReference = + visibleCommit == null ? "genesis:" + sharedGenesisReceipt : visibleCommit.toString(); + return new SourceHead(row.get("source_epoch", String.class), baseReference); + } + + private static DraftCommitBinding.RevisionPayload policyDeleteRevision( + String order, UUID revisionId, String logicalId, String world, String realm) { + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"" + + logicalId + + "\",\"operation\":\"DELETE\",\"worldSlug\":\"" + + world + + "\",\"realmSlug\":\"" + + realm + + "\"}"; + return new DraftCommitBinding.RevisionPayload( + order, revisionId, Owner.GAME_DESIGN_CONTROL_PLANE, payload); + } + + private static DraftCommitBinding.RevisionPayload policyUpsertRevision( + String order, + UUID revisionId, + String logicalId, + String world, + String realm, + boolean production) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"World\",\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"" + + logicalId + + "\",\"policy\":" + + policy.canonicalJson() + + "}"; + return new DraftCommitBinding.RevisionPayload( + order, revisionId, Owner.GAME_DESIGN_CONTROL_PLANE, payload); + } + + private static DraftCommitBinding commandOnlyBinding( + Fixture fixture, UUID baseCommitId, String expectedCommandEpoch) { + TargetProof target = fixture.target(); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + baseCommitId.toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"ISOLATED-command\"," + + "\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," + + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + target.canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + expectedCommandEpoch))); + } + + private static Fixture freshFixture() { + String schema = "gd_policy_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); + var transactions = new DataSourceTransactionManager(dataSource); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var target = + write.execute( + status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED policy source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return target(version); + }); + var policies = new RealmPolicySourceRepository(dsl); + var sources = new GameDesignSourceRepository(dsl); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var fixture = + new Fixture( + dataSource, + schema, + dsl, + write, + target, + null, + policies, + sources, + coordinator, + new RealmPolicySourceService(policies, transactions)); + var baseline = policyBinding(fixture, "main", true); + return new Fixture( + dataSource, + schema, + dsl, + write, + target, + baseline, + policies, + sources, + coordinator, + new RealmPolicySourceService(policies, transactions)); + } + + private static Fixture policyFixture() { + var fixture = freshFixture(); + var baseline = fixture.baseline(); + start(fixture, baseline); + var applied = fixture.tx(() -> fixture.sources().apply(baseline).policy().orElseThrow()); + synchronize(fixture, baseline, applied); + return fixture; + } + + private static Fixture retainedFixture() { + String schema = "gd_policy_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + migrate(dataSource, schema, "50.7"); + var transactions = new DataSourceTransactionManager(dataSource); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var game = + write.execute( + status -> { + var created = new Game(); + created.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + created.setName("ISOLATED retained policy source"); + return new GameRepository(dsl).save(created); + }); + var version = write.execute(status -> insertRetainedVersion(dsl, properties, game, 1)); + migrate(dataSource, schema, "50.13"); + var target = target(version); + var baseline = historicalPolicyBinding(target, "0", "main", true); + var policies = new RealmPolicySourceRepository(dsl); + var sources = new GameDesignSourceRepository(dsl); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var fixture = + new Fixture( + dataSource, + schema, + dsl, + write, + target, + baseline, + policies, + sources, + coordinator, + new RealmPolicySourceService(policies, transactions)); + // Retained fixtures start at V50.13; history tests seed there before migration, while denial + // tests advance without adding provenance. + return fixture; + } + + private static void migrateLatest(Fixture fixture) { + migrate(fixture.dataSource(), fixture.schema(), "latest"); + } + + private static RealmPolicySnapshot seedRetainedSnapshot(Fixture fixture, String sourceEpoch) { + // This is only a V50.13 historical row fixture: it creates no reviewed-base evidence and is + // never used for a current source application. + return fixture.tx( + () -> { + var binding = fixture.baseline(); + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-initial-owner-baseline", + "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + BigInteger.ONE.toString()))); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + fixture.coordinator().releaseApplicationSlot(binding); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + snapshot.canonicalJson()); + return snapshot; + }); + } + + private static UUID visiblePointerCommit(Fixture fixture) { + var pointer = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT commit_id FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "synchronized Draft commit should retain its visibility pointer"); + return pointer.get("commit_id", UUID.class); + } + + private static void migrate(DriverManagerDataSource dataSource, String schema, String target) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target(target) + .load() + .migrate(); + } + + private static Version insertRetainedVersion( + DSLContext dsl, PostgresProperties properties, Game game, int versionNumber) { + var inserted = + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " + + "'ISOLATED retained source fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + versionNumber, + game.getId()); + if (inserted == null) { + throw new IllegalStateException("ISOLATED retained Game Design source row is absent"); + } + return new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private record SourceHead(String sourceEpoch, String baseReference) {} + + private record Fixture( + DriverManagerDataSource dataSource, + String schema, + DSLContext dsl, + TransactionTemplate write, + TargetProof target, + DraftCommitBinding baseline, + RealmPolicySourceRepository policies, + GameDesignSourceRepository sources, + DraftCommitCoordinatorRepository coordinator, + RealmPolicySourceService reads) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..cd10f8ad79 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -0,0 +1,1479 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.ForwardingServerCall; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Actual GD owner DB guard proof; every upstream creator/source/freeze input is ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignPublicationOperationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final AtomicLong TEST_CERTIFICATE_SERIAL = new AtomicLong(1); + + /** + * Genuine GD SQL result and physical workload identity; upstream creator/export/freeze remain + * ISOLATED. + */ + @Test + void + physicalMtlsTerminalReadRecoversActualPublishedAndNoPublicationOwnerSealsAndRejectsWrongPeers( + @TempDir Path directory) throws Exception { + var pki = publicationReadPki(); + int ownerIndex = 0; + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + byte[] retained = original.terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var headers = new AtomicInteger(); + var loseResponse = new AtomicBoolean(true); + var server = publicationReadServer(fixture, pki.server(), pki.ca(), headers, loseResponse); + try { + try (var client = + publicationReadClient( + server, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-account"))) { + client.init(); + // The real handler and owner read finish; the first outbound result is deliberately lost. + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + var recovered = client.read(request).terminalEvidence().orElseThrow(); + assertThat(recovered.canonicalBytes()).isEqualTo(retained); + assertThat(recovered.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + assertThat(recovered.outcome().name()) + .isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + if (published) { + assertThat(recovered.publicationVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(recovered.publishedReleaseBundleDigest()) + .isEqualTo(recovered.releaseContent().contentDigest()); + } else + assertThatThrownBy(recovered::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); + assertThat(client.read(request).terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo(retained); + } + for (var identity : + java.util.List.of(pki.wrongCallerService(), pki.wrongCallerNamespace())) { + try (var client = + publicationReadClient( + server, + identity, + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + identity.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + } + } + assertThat(headers).hasValue(5); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + for (var wrongServer : + java.util.List.of(pki.wrongServerService(), pki.wrongServerNamespace())) { + var deniedHeaders = new AtomicInteger(); + var deniedServer = + publicationReadServer( + fixture, wrongServer, pki.ca(), deniedHeaders, new AtomicBoolean(false)); + try (var client = + publicationReadClient( + deniedServer, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + wrongServer.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + assertThat(deniedHeaders).hasValue(0); + } finally { + deniedServer.shutdownNow(); + assertThat(deniedServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isEqualTo(retained); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + ownerIndex++; + } + } + + private Server publicationReadServer( + Fixture fixture, + TestCertificate identity, + X509Certificate ca, + AtomicInteger headers, + AtomicBoolean loseResponse) + throws Exception { + ServerInterceptor responseLoss = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean dropped; + + @Override + public void sendMessage(RespT message) { + if (loseResponse.compareAndSet(true, false)) dropped = true; + else super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + super.close( + dropped + ? Status.UNAVAILABLE.withDescription( + "ISOLATED lost terminal read response") + : status, + trailers); + } + }, + metadata); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(ca) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new GameDesignPublicationTerminalReadGrpcService(fixture.service(), "test"), + responseLoss, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameDesignPublicationTerminalClient publicationReadClient( + Server server, TestCertificate identity, X509Certificate ca, Path directory) + throws Exception { + Files.createDirectories(directory); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + publicationReadPem( + directory.resolve("client.crt"), "CERTIFICATE", identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + publicationReadPem( + directory.resolve("client.key"), "PRIVATE KEY", identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + publicationReadPem(directory.resolve("ca.crt"), "CERTIFICATE", ca.getEncoded()).toString()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new GameDesignPublicationTerminalClient( + endpoints, tls, new GrpcChannelFactory(), "test"); + } + + private static Path publicationReadPem(Path path, String type, byte[] bytes) throws Exception { + Files.writeString( + path, + "-----BEGIN " + + type + + "-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes) + + "\n-----END " + + type + + "-----\n"); + return path; + } + + private static TestPki publicationReadPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + Security.addProvider(new BouncyCastleProvider()); + var keys = publicationReadKeyPair(); + var name = new X500Name("CN=Game Design PostgreSQL Terminal Test CA, O=FireMUD Test"); + var ca = + publicationReadCertificate(name, keys.getPublic(), name, keys.getPrivate(), true, null); + return new TestPki( + ca, + publicationReadLeaf( + name, keys.getPrivate(), "server", "spiffe://firemud/ns/test/sa/game-design-service"), + publicationReadLeaf( + name, keys.getPrivate(), "account", "spiffe://firemud/ns/test/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-namespace", + "spiffe://firemud/ns/other/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-service", + "spiffe://firemud/ns/test/sa/world-management-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-namespace", + "spiffe://firemud/ns/other/sa/game-design-service")); + } + + private static TestCertificate publicationReadLeaf( + X500Name ca, PrivateKey issuerKey, String label, String uri) throws Exception { + var keys = publicationReadKeyPair(); + var names = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, uri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + return new TestCertificate( + label, + keys.getPrivate(), + publicationReadCertificate( + new X500Name("CN=" + label + ", O=FireMUD Test"), + keys.getPublic(), + ca, + issuerKey, + false, + names)); + } + + private static X509Certificate publicationReadCertificate( + X500Name subject, + java.security.PublicKey key, + X500Name issuer, + PrivateKey issuerKey, + boolean ca, + GeneralNames names) + throws Exception { + var start = Instant.now().minusSeconds(60); + var builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(TEST_CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(start), + Date.from(start.plusSeconds(60L * 60L * 24L * 14L)), + subject, + key); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage( + ca + ? KeyUsage.keyCertSign | KeyUsage.cRLSign + : KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + if (!ca) { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, names); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey))); + } + + private static KeyPair publicationReadKeyPair() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate( + String label, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate ca, + TestCertificate server, + TestCertificate account, + TestCertificate wrongCallerService, + TestCertificate wrongCallerNamespace, + TestCertificate wrongServerService, + TestCertificate wrongServerNamespace) {} + + @Test + void authenticatedTerminalReadDispatchesActualStoredPublishedAndNoPublicationEvidence() + throws Exception { + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var expected = + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + for (String peer : java.util.List.of("account-service", "world-management-service")) { + var result = readThroughHandler(fixture, request, peer); + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, result.response); + assertThat(evidence.terminalEvidence().orElseThrow().canonicalBytes()).isEqualTo(expected); + assertThat(evidence.status().name()).isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + } + } + } + + @Test + void authenticatedTerminalReadMapsTransactionFailuresToUnavailable() throws Exception { + var fixture = fixture(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + PlatformTransactionManager failingTransactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + throw new TransactionException("ISOLATED transaction manager failure") {}; + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }; + var owner = + new GameDesignPublicationOperationService( + new GameDesignPublicationOperationRepository(fixture.dsl()), failingTransactions); + + var result = readThroughHandler(fixture, request, "account-service", owner); + + assertThat(result.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.response).isNull(); + assertThat(result.completed).isFalse(); + } + + @Test + void authenticatedTerminalReadMapsResponseEncodingFailuresWithoutPartialResponses() + throws Exception { + var fixture = fixture(); + publish(fixture); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + + for (RuntimeException encodingFailure : + List.of( + new IllegalArgumentException("ISOLATED invalid response"), + new IllegalStateException("ISOLATED inconsistent response"), + new RuntimeException("ISOLATED response encoder failure"))) { + try (var codec = + org.mockito.Mockito.mockStatic( + GameDesignPublicationTerminalReadGrpcCodec.class, + org.mockito.Mockito.CALLS_REAL_METHODS)) { + codec + .when( + () -> + GameDesignPublicationTerminalReadGrpcCodec.toResponse( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenThrow(encodingFailure); + + var result = readThroughHandler(fixture, request, "account-service"); + + Status.Code expected = + encodingFailure instanceof IllegalArgumentException + || encodingFailure instanceof IllegalStateException + ? Status.Code.FAILED_PRECONDITION + : Status.Code.INTERNAL; + assertThat(result.error).isEqualTo(expected); + assertThat(result.response).isNull(); + assertThat(result.completed).isFalse(); + } + } + } + + @Test + void authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation() throws Exception { + var fixture = fixture(); + var pending = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var result = readThroughHandler(fixture, pending, "world-management-service"); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(pending, result.response); + assertThat(evidence.status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(evidence.terminalEvidence()).isEmpty(); + var absentOperation = + IsolatedPublicationOperationFixtures.fresh( + fixture.operation().account().input().selection().target()); + var absent = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", absentOperation.canonicalBytes()); + var absentResult = readThroughHandler(fixture, absent, "account-service"); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(absent, absentResult.response) + .status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + + @Test + void retainedV50_6TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() + throws Exception { + var fixture = fixture("50.6"); + assertThat(fixture.candidate()).isNull(); + var op = fixture.operation(); + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "NO_PUBLICATION"); + // V50.6 framed nullable release_row_json as a present, zero-byte fourth frame for + // NO_PUBLICATION. Preserve that historical encoding exactly without routing an empty value + // through the nonempty canonical-text helper. + DraftAuthorizationFenceBinding.frame(old, new byte[0]); + fixture + .write() + .executeWithoutResult( + status -> { + var attempt = + fixture + .attempts() + .findByPublishWorkflowIdForUpdate(op.workflowId()) + .orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + fixture.attempts().save(attempt); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + op.workflowId()); + }); + fixture.completeMigration().run(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create("test", op.canonicalBytes()); + var result = readThroughHandler(fixture, request, "account-service"); + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + var retained = fixture.service().readExact(op).orElseThrow(); + assertThat(retained.receiptBytes()).isEqualTo(old.toByteArray()); + assertThat(retained.terminalEvidenceBytes()).isNull(); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT publication_version_state_epoch FROM game_design_publication_operation WHERE publish_workflow_id = ?", + op.workflowId())) + .get(0)) + .isNull(); + } + + @Test + void publicationReceiptSurvivesAdditiveReleaseColumnAndFreshSealAfterAddition() throws Exception { + var retained = fixture(); + publish(retained); + var original = retained.service().readExact(retained.operation()).orElseThrow(); + String originalEvidence = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT release_row_json FROM game_design_publication_operation WHERE publish_workflow_id = ?", + retained.operation().workflowId()), + "Expected retained publication operation row") + .get("release_row_json", String.class); + String originalWholeRow = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()), + "Expected original published release row") + .get("evidence", String.class); + assertThat(originalEvidence).isEqualTo(originalWholeRow); + + retained.completeMigration().run(); + retained + .write() + .executeWithoutResult( + status -> + retained + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + String expandedWholeRow = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()), + "Expected published release row after additive column") + .get("evidence", String.class); + assertThat(expandedWholeRow).isNotEqualTo(originalEvidence); + var replay = retained.service().readExact(retained.operation()).orElseThrow(); + assertThat(replay.receiptBytes()).isEqualTo(original.receiptBytes()); + assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); + assertThatThrownBy( + () -> + retained + .write() + .executeWithoutResult( + status -> + retained + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()))) + .isInstanceOf(RuntimeException.class); + assertThat(retained.service().readExact(retained.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + + var fresh = fixture(); + fresh.completeMigration().run(); + fresh + .write() + .executeWithoutResult( + status -> + fresh + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + publish(fresh); + var freshRead = fresh.service().readExact(fresh.operation()).orElseThrow(); + assertThat(freshRead.outcome()).isEqualTo("PUBLISHED"); + assertThat(freshRead.receiptBytes()).isNotNull(); + assertThat(fresh.service().readExact(fresh.operation()).orElseThrow().receiptBytes()) + .isEqualTo(freshRead.receiptBytes()); + } + + private ReadCollector readThroughHandler( + Fixture fixture, + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + String service) { + return readThroughHandler(fixture, request, service, fixture.service()); + } + + private ReadCollector readThroughHandler( + Fixture fixture, + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + String service, + GameDesignPublicationOperationService owner) { + var handler = new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + var collector = new ReadCollector(); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + service, "test", service)); + var previous = context.attach(); + try { + handler.readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), collector); + } finally { + context.detach(previous); + } + return collector; + } + + private static final class ReadCollector + implements StreamObserver { + private ReadGameDesignPublicationTerminalResponse response; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadGameDesignPublicationTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final String ASSET_FILE_NAME = "publication-operation-logo.png"; + private static final String ASSET_CONTENT_TYPE = "image/png"; + private static final byte[] ASSET_BYTES = + "isolated publication asset bytes".getBytes(StandardCharsets.UTF_8); + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + + @Test + void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() + throws Exception { + var fixture = fixture(); + noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); + var noPublication = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + assertThat(noPublication.outcome()) + .isEqualTo(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + assertThatThrownBy(noPublication::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .operations() + .requirePending( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SEALED_OR_CHANGED"); + assertThatThrownBy( + () -> fixture.write().executeWithoutResult(status -> rawReleaseInsert(fixture))) + .hasMessageContaining("selected publication is absent, sealed, or changed"); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + } + + @Test + void terminalEvidenceKeepsOriginalCommittedEpochAfterLaterVersionTransition() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + long captured = terminal.publicationVersionStateEpoch(); + assertThat(captured).isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(terminal.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + fixture + .write() + .executeWithoutResult( + status -> { + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(captured + 1); + fixture.versions().save(version); + }); + var replay = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(replay.terminalEvidenceBytes()) + .publicationVersionStateEpoch()) + .isEqualTo(captured); + } + + @Test + void terminalExtensionRefusesRawEpochDigestBytesAndReleaseContentSubstitution() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + for (String assignment : + java.util.List.of( + "publication_version_state_epoch = publication_version_state_epoch + 1", + "published_release_bundle_digest = 'sha256:' || repeat('f', 64)", + "terminal_evidence_bytes = terminal_evidence_bytes || decode('00', 'hex')", + "release_content_bytes = release_content_bytes || decode('00', 'hex')")) { + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET " + + assignment + + " WHERE publish_workflow_id = ?", + fixture.operation().workflowId()))) + .hasMessageContaining("publication operation identity or terminal outcome is immutable"); + } + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes()) + .isEqualTo(original.terminalEvidenceBytes()); + } + + @Test + void originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows() throws Exception { + for (String forgedField : java.util.List.of("epoch", "digest", "content", "terminal")) { + String expectedGuardMessage = + forgedField.equals("terminal") + ? "publication terminal bytes differ from original owner result" + : "publication terminal content or committed epoch differs from owner seal"; + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture, false); + rawTerminalSeal(fixture, forgedField); + })) + .hasMessageContaining(expectedGuardMessage); + var pending = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(pending.outcome()).isEqualTo("PENDING"); + assertThat(pending.terminalEvidenceBytes()).isNull(); + publish(fixture); + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isNotNull(); + } + } + + @Test + void publicationSealEpochMustRemainTheActualVersionEpochThroughCommit() throws Exception { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + fixture + .dsl() + .execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE tenant_id = ? AND id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()); + })) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + + @Test + void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() + throws Exception { + var fixture = fixture(); + var staleFailure = + fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("PUBLISHED"); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + staleFailure.setStatus(PublishAttemptStatus.FAILED); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult(status -> fixture.attempts().save(staleFailure))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("CAS_CONFLICT"); + assertThatThrownBy(() -> noPublication(fixture)).isInstanceOf(IllegalStateException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + } + + @Test + void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() + throws Exception { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + throw new IllegalStateException( + "ISOLATED rollback after all owner writes"); + })) + .hasMessageContaining("rollback after all owner writes"); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat( + fixture + .attempts() + .findByPublishWorkflowId(fixture.operation().workflowId()) + .orElseThrow() + .getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + publish(fixture); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PUBLISHED"); + } + + @Test + void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exception { + var fixture = fixture(); + var sealed = new CountDownLatch(1); + var releaseSeal = new CountDownLatch(1); + var attempting = new CountDownLatch(1); + var winnerPid = new AtomicInteger(); + var loserPid = new AtomicInteger(); + try (var executor = Executors.newFixedThreadPool(2)) { + var winner = + executor.submit( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + noPublicationInTransaction(fixture); + winnerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "no-publication transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + sealed.countDown(); + await(releaseSeal); + })); + assertThat(sealed.await(10, TimeUnit.SECONDS)).isTrue(); + var loser = + executor.submit( + () -> { + fixture + .write() + .executeWithoutResult( + status -> { + loserPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "late publisher transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + assertThatThrownBy(() -> publishInTransaction(fixture)) + .isInstanceOf(IllegalStateException.class); + }); + }); + assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); + boolean observedBlock = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var activity = + fixture + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' " + + "AND query LIKE 'SELECT id FROM game WHERE tenant_id%' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + winnerPid.get(), loserPid.get()); + if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { + observedBlock = true; + break; + } + Thread.sleep(25); + } + assertThat(observedBlock) + .as("late publisher backend blocked by no-publication winner on the game owner lock") + .isTrue(); + releaseSeal.countDown(); + winner.get(10, TimeUnit.SECONDS); + loser.get(10, TimeUnit.SECONDS); + } finally { + releaseSeal.countDown(); + } + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("NO_PUBLICATION"); + } + + private void noPublication(Fixture fixture) { + fixture.write().executeWithoutResult(status -> noPublicationInTransaction(fixture)); + } + + private void noPublicationInTransaction(Fixture fixture) { + var op = fixture.operation(); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_BUSINESS_DENIAL"); + fixture.attempts().save(attempt); + // Emulate the historical V50.6/V50.7 seal storage directly. The current attempt wrapper also + // writes the V50.9 realm-policy association, which is absent from these schemas. + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), false); + } + + private void publish(Fixture fixture) { + fixture.write().executeWithoutResult(status -> publishInTransaction(fixture)); + } + + private void publishInTransaction(Fixture fixture) { + publishInTransaction(fixture, true); + } + + private void publishInTransaction(Fixture fixture, boolean seal) { + var op = fixture.operation(); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + fixture.releases().save(bundle(fixture)); + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(version.getVersionStateEpoch() + 1); + fixture.versions().save(version); + var artifact = + fixture + .artifacts() + .findByTenantIdAndVersionIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + fixture.artifacts().save(artifact); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + fixture.attempts().save(attempt); + if (seal) { + // Emulate the historical V50.6/V50.7 seal storage without querying the V50.9 policy + // association. + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + } + } + + /** + * Attempts a raw first seal, so failures prove content/epoch binding rather than only + * immutability. + */ + private void rawTerminalSeal(Fixture fixture, String forgedField) { + var op = fixture.operation(); + var row = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence, publication_release_content(r) AS content, 'sha256:' || encode(sha256(publication_release_content(r)), 'hex') AS digest FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + op.tenantKey(), + op.versionId())); + String evidence = row.get("evidence", String.class); + byte[] content = row.get("content", byte[].class); + String digest = row.get("digest", String.class); + long epoch = op.world().request().versionStateEpoch() + 1; + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(old, evidence); + var terminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(terminal, "game-design-publication-terminal/v1"); + DraftAuthorizationFenceBinding.frame(terminal, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(terminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(terminal, content); + DraftAuthorizationFenceBinding.frame(terminal, Long.toString(epoch)); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'PUBLISHED', revision = revision + 1, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + evidence, + forgedField.equals("terminal") ? new byte[] {1} : terminal.toByteArray(), + forgedField.equals("epoch") ? epoch + 1 : epoch, + forgedField.equals("content") ? new byte[] {1} : content, + forgedField.equals("digest") ? "sha256:" + "f".repeat(64) : digest, + op.workflowId()); + } + + private PublishedReleaseBundle bundle(Fixture fixture) { + var op = fixture.operation(); + var bundle = new PublishedReleaseBundle(); + bundle.setTenantId(op.tenantKey()); + bundle.setVersionId(op.versionId()); + bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(op.account().tenantId()); + bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(op.workflowId()); + bundle.setManifestHash(fixture.candidate().manifest().manifestHash()); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson( + new ObjectMapper().writeValueAsString(fixture.candidate().manifest().artifactDigests())); + bundle.setRequiredManifestAssetKeysJson( + new ObjectMapper() + .writeValueAsString(fixture.candidate().manifest().requiredManifestAssetKeys())); + bundle.setCommandDefinitionsJson("[]"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants( + op.versionId(), + op.world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private void rawReleaseInsert(Fixture fixture) { + var bundle = bundle(fixture); + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, attestation_schema_version, publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, " + + "artifact_digests_json, required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, world_published_start_location_evidence_json) " + + "VALUES (?, ?, 1, ?, ?, ?, 'v2', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + bundle.getTenantId(), + bundle.getVersionId(), + bundle.getCanonicalTenantId(), + bundle.getCanonicalVersionId(), + UUID.randomUUID().toString(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getGenerationConfigRevision(), + bundle.getParticipantDigestsJson(), + bundle.getWorldPublishedStartLocationEvidenceJson()); + } + + private Fixture fixture() throws Exception { + return fixture("50.7"); + } + + private Version insertRetainedVersion( + DSLContext dsl, VersionRepository versions, Game game, int versionNumber) { + var inserted = + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " + + "'ISOLATED retained publication operation fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + versionNumber, + game.getId()); + if (inserted == null) { + throw new IllegalStateException("ISOLATED retained Game Design owner row is absent"); + } + return versions.findById(inserted.get("id", Long.class)).orElseThrow(); + } + + private Fixture fixture(String migrationTarget) throws Exception { + String schema = "gd_pub_op_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target(migrationTarget) + .load() + .migrate(); + var transactions = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var configuration = new org.jooq.impl.DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set( + new org.jooq.impl.DataSourceConnectionProvider( + new TransactionAwareDataSourceProxy(source))); + configuration.set( + new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(transactions)); + var dsl = DSL.using(configuration); + var games = new GameRepository(dsl); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var versions = new VersionRepository(dsl); + Game game = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED publication owner"); + return games.save(requested); + }); + // These V50.6/V50.7 cases model retained history. Insert the canonical owner row before V50.8 + // so + // the current VersionRepository does not enroll it in post-V50.7 source storage. + Version version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var operation = + write.execute( + status -> { + try { + return IsolatedPublicationOwnerSetup.retain( + dsl, target, version.getVersionStateEpoch()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var operations = new GameDesignPublicationOperationRepository(dsl); + FrozenAssetExportCandidate readCandidate = null; + if (!"50.6".equals(migrationTarget)) { + var gameAssets = new GameAssetRepository(dsl); + var asset = + write.execute( + status -> { + var requested = new GameAsset(); + requested.setTenantId(game.getTenantId()); + requested.setFileName(ASSET_FILE_NAME); + requested.setContentType(ASSET_CONTENT_TYPE); + requested.setData(ASSET_BYTES); + return gameAssets.save(requested); + }); + var publicationRepository = new VersionAssetPublicationRepository(dsl); + write.executeWithoutResult( + status -> + publicationRepository.associateDraftAsset( + game.getTenantId(), version.getId(), asset.getId(), "logo")); + var snapshot = + write.execute( + status -> + publicationRepository.freezeOrReadSnapshot( + game.getTenantId(), version.getVersionNumber())); + var artifactService = + new VersionAssetArtifactServiceImpl( + new VersionAssetArtifactRepository(dsl), + null, + versions, + null, + null, + null, + null, + null, + new ObjectMapper()); + write.execute( + status -> + artifactService.stageExport( + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + var artifacts = new VersionAssetArtifactRepository(dsl); + var candidateService = + new VersionAssetExportCandidateServiceImpl( + versions, + games, + new PublishAttemptRepository(dsl), + artifacts, + publicationRepository, + transactions, + new ObjectMapper()); + var requestedCandidate = candidate(snapshot); + var committedCandidate = + candidateService.recordExportCandidate( + game.getTenantId(), version.getVersionNumber(), requestedCandidate); + readCandidate = + candidateService.readExportCandidate(game.getTenantId(), version.getVersionNumber()); + assertThat(committedCandidate).isEqualTo(requestedCandidate); + assertThat(readCandidate).isEqualTo(committedCandidate); + } + var artifacts = new VersionAssetArtifactRepository(dsl); + return new Fixture( + dsl, + write, + versions, + new PublishAttemptRepository(dsl), + new PublishedReleaseBundleRepository(dsl), + artifacts, + operations, + new GameDesignPublicationOperationService(operations, transactions), + operation, + readCandidate, + () -> + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate()); + } + + private FrozenAssetExportCandidate candidate( + VersionAssetPublicationRepository.ExportSnapshot snapshot) { + var source = snapshot.items().get(0); + String contentDigest = source.contentDigest(); + String objectKey = "artifacts/sha256/" + contentDigest.substring("sha256:".length()); + var digest = + new PublishedArtifactDigest( + source.usageKey(), "BINARY", objectKey, contentDigest, source.contentType(), 1); + String url = PUBLIC_BASE_URL + "/" + objectKey; + String manifestJson = + "{\"schemaVersion\":1,\"assets\":{\"" + + source.usageKey() + + "\":{\"usageKey\":\"" + + source.usageKey() + + "\",\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + objectKey + + "\",\"contentDigest\":\"" + + contentDigest + + "\",\"contentType\":\"" + + source.contentType() + + "\",\"artifactSchemaVersion\":1,\"producerService\":\"game-design-service\",\"versionId\":\"" + + snapshot.canonicalVersionId() + + "\",\"url\":\"" + + url + + "\"}}}"; + return new FrozenAssetExportCandidate( + new ExportedAssetManifest( + sha256(manifestJson.getBytes(StandardCharsets.UTF_8)), + 1, + List.of(source.usageKey()), + List.of(digest)), + PUBLIC_BASE_URL); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("ISOLATED barrier timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + VersionRepository versions, + PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, + VersionAssetArtifactRepository artifacts, + GameDesignPublicationOperationRepository operations, + GameDesignPublicationOperationService service, + GameDesignPublicationOperation operation, + FrozenAssetExportCandidate candidate, + Runnable completeMigration) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java new file mode 100644 index 0000000000..51996e07c8 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -0,0 +1,863 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +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.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListener; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.Test; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; +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; +import tools.jackson.databind.ObjectMapper; + +/** Actual Game Design terminal and release rows; the policy author's source input is ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class RealmPolicyPublicationPostgresIntegrationTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final List PUBLISHED_SET_COLUMNS = + List.of( + "canonical_tenant_id", + "canonical_version_id", + "game_design_version_row_id", + "version_number", + "source_commit_id", + "source_epoch", + "target_proof_json", + "operation_bytes", + "capture_bytes", + "terminal_evidence_bytes", + "release_content_bytes", + "published_release_bundle_ref", + "published_release_bundle_digest", + "publish_workflow_id", + "manifest_hash", + "publication_version_state_epoch", + "policy_count", + "policy_set_digest", + "sealed"); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exception { + Fixture fixture = fixture(true); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, false); + + var originalOwnerRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + String originalReleaseEvidence = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT release_row_json FROM game_design_publication_operation WHERE publish_workflow_id = ?", + operation.workflowId()), + "Expected retained policy publication operation row") + .get("release_row_json", String.class); + String originalWholeReleaseRow = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()), + "Expected original policy published release row") + .get("evidence", String.class); + assertThat(originalReleaseEvidence).isEqualTo(originalWholeReleaseRow); + + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); + String expandedWholeReleaseRow = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()), + "Expected policy published release row after additive column") + .get("evidence", String.class); + assertThat(expandedWholeReleaseRow).isNotEqualTo(originalReleaseEvidence); + var retainedOwnerRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThat(retainedOwnerRead.receiptBytes()).isEqualTo(originalOwnerRead.receiptBytes()); + assertThat(retainedOwnerRead.terminalEvidenceBytes()) + .isEqualTo(originalOwnerRead.terminalEvidenceBytes()); + + var original = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(original.policies()).hasSize(1); + assertThat(original.policyCount()).isEqualTo(1); + assertThat(original.policies().getFirst().policyId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(original.policies().getFirst().source().revisionId()) + .isEqualTo(fixture.baseline().revisions().getFirst().revisionId()); + assertThat(original.policies().getFirst().source().commitId()) + .isEqualTo(fixture.baseline().commitId()); + assertThat(original.publishWorkflowId()).isEqualTo(operation.workflowId()); + assertThat(original.publicationVersionStateEpoch()) + .isEqualTo(operation.world().request().versionStateEpoch() + 1); + assertRejectedHeaderClonesPreserveOriginal(fixture, original); + + var exactRetry = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertThat(exactRetry.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat(exactRetry.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(exactRetry.operationBytes()).containsExactly(original.operationBytes()); + assertThat(exactRetry.captureBytes()).containsExactly(original.captureBytes()); + assertThat(exactRetry.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + + fixture.moveVersion(VersionLifecycleState.ACTIVE, original.publicationVersionStateEpoch() + 1); + var activeRead = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(activeRead.publicationVersionStateEpoch()) + .isEqualTo(original.publicationVersionStateEpoch()); + assertThat(activeRead.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat( + fixture + .publicationReads() + .readPublishedPolicy(fixture.target(), "world", "main") + .orElseThrow() + .policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + var retryAfterActivation = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertThat(retryAfterActivation.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat(retryAfterActivation.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(retryAfterActivation.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_published_realm_policy_set " + + "SET policy_set_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + "sha256:" + "f".repeat(64), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .isInstanceOf(RuntimeException.class); + + Fixture fresh = fixture(true); + fresh.tx( + () -> { + fresh + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); + GameDesignPublicationOperation freshOperation = fresh.prepare(true); + fresh.writePublish(freshOperation, false); + var freshRead = fresh.publicationReads().readPublishedSet(fresh.target()).orElseThrow(); + assertThat(freshRead.policies()).hasSize(1); + assertThat(freshRead.policyCount()).isEqualTo(1); + assertThat( + fresh + .publicationReads() + .readPublishedPolicy(fresh.target(), "world", "main") + .orElseThrow() + .policyId()) + .isEqualTo(freshRead.policies().getFirst().policyId()); + var freshOwnerRead = fresh.operations().read(freshOperation.workflowId()).orElseThrow(); + assertThat(freshOwnerRead.outcome()).isEqualTo("PUBLISHED"); + byte[] freshReceipt = freshOwnerRead.receiptBytes(); + assertThat(freshReceipt).isNotNull(); + var freshRetry = + fresh.tx( + () -> + fresh + .publicationWrites() + .retainSealedPublished(freshOperation.workflowId()) + .orElseThrow()); + assertThat(freshRetry.policies().getFirst().policyId()) + .isEqualTo(freshRead.policies().getFirst().policyId()); + assertThat(freshRetry.operationBytes()).containsExactly(freshRead.operationBytes()); + assertThat(freshRetry.captureBytes()).containsExactly(freshRead.captureBytes()); + assertThat(freshRetry.terminalEvidenceBytes()) + .containsExactly(freshRead.terminalEvidenceBytes()); + assertThat(fresh.operations().read(freshOperation.workflowId()).orElseThrow().receiptBytes()) + .isEqualTo(freshReceipt); + } + + @Test + void openSetRejectsReplacedSourceAndWrongOrdinalWhileKeepingInheritedProvenance() + throws Exception { + Fixture fixture = fixture(true); + var stale = + fixture + .policySource() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow() + .policies() + .getFirst(); + // A second stipulated ISOLATED owner baseline replaces the main policy. The genuine + // publication selection then inherits it through the ordinary frozen-source path. + var replacementBinding = + fixture.tx( + () -> + baseline( + fixture.target(), + fixture.dsl(), + new GameDesignSourceRepository(fixture.dsl()), + "Replacement World")); + GameDesignPublicationOperation operation = fixture.prepare(true); + var selected = fixture.policySource().readCapture(operation).orElseThrow().snapshot(); + var replacement = selected.policies().getFirst(); + assertThat(selected.binding().commitId()).isNotEqualTo(replacementBinding.commitId()); + assertThat(replacement.commitId()).isEqualTo(replacementBinding.commitId()); + assertThat(replacement.revisionId()) + .isEqualTo(replacementBinding.revisions().getFirst().revisionId()); + + var probes = new AtomicInteger(); + var configuration = fixture.dsl().configuration(); + var previousListeners = configuration.executeListenerProviders(); + configuration.set( + new DefaultExecuteListenerProvider( + new ExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.startsWith("INSERT INTO game_design_published_realm_policy_set ")) + return; + assertRejectedOpenSetPolicy(fixture, operation, stale, 0); + assertRejectedOpenSetPolicy(fixture, operation, replacement, 1); + probes.incrementAndGet(); + } + })); + try { + fixture.writePublish(operation, false); + } finally { + configuration.set(previousListeners); + } + assertThat(probes.get()).isEqualTo(1); + var published = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(published.sourceCommitId()).isEqualTo(selected.binding().commitId()); + assertThat(published.policies()).hasSize(1); + assertThat(published.policies().getFirst().source()).isEqualTo(replacement); + var retry = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertPublishedSetUnchanged(published, retry); + assertPublishedSetUnchanged( + published, fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow()); + } + + private static void assertRejectedOpenSetPolicy( + Fixture fixture, + GameDesignPublicationOperation operation, + RealmPolicySource.Policy source, + int ordinal) { + var policy = source.policy(); + UUID policyId = UUID.randomUUID(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + fixture + .operations() + .read(operation.workflowId()) + .orElseThrow() + .terminalEvidenceBytes()); + var release = terminal.releaseContent(); + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, + fixture.target(), + release.versionNumber(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source); + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + nested -> + DSL.using(nested) + .execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + ordinal, + policyId, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + digest, + policy.visible(), + policy.publicProduction()))) + .satisfies( + failure -> + assertThat(rootCause(failure).getMessage()) + .contains( + "published realm policy row differs from exact captured source revision")); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))).isZero(); + } + + @Test + void sealRollbackLeavesNoAssociationAndExactPublicationRetryAllocatesOneStableIdentity() + throws Exception { + Fixture fixture = fixture(true); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, true); + + assertThat(fixture.operations().read(operation.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))).isZero(); + + fixture.writePublish(operation, false); + var first = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + fixture.tx(() -> fixture.publicationWrites().retainSealedPublished(operation.workflowId())); + var replay = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(replay.policies().getFirst().policyId()) + .isEqualTo(first.policies().getFirst().policyId()); + assertThat(replay.policySetDigest()).isEqualTo(first.policySetDigest()); + } + + @Test + void missingPolicyCaptureFailsClosedForEveryFullVersionRelease() throws Exception { + Fixture unrelated = fixture(false); + GameDesignPublicationOperation noPolicy = unrelated.prepare(false); + assertThatThrownBy(() -> unrelated.writePublish(noPolicy, false)) + .hasMessageContaining("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + assertThat(unrelated.operations().read(noPolicy.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat(unrelated.publicationReads().readPublishedSet(unrelated.target())).isEmpty(); + + Fixture missingCapture = fixture(true); + GameDesignPublicationOperation policyOperation = missingCapture.prepare(false); + assertThatThrownBy(() -> missingCapture.writePublish(policyOperation, false)) + .hasMessageContaining("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + assertThat( + missingCapture.operations().read(policyOperation.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat(missingCapture.publicationReads().readPublishedSet(missingCapture.target())) + .isEmpty(); + } + + private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception { + String schema = "gd_realm_policy_pub_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + migrate(source, schema); + var transactions = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var configuration = new DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(source))); + configuration.set(new SpringTransactionProvider(transactions)); + var dsl = DSL.using(configuration); + var sources = new GameDesignSourceRepository(dsl); + var policySource = new RealmPolicySourceRepository(dsl); + var games = new GameRepository(dsl); + var versions = new VersionRepository(dsl); + Game game = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED realm policy publication"); + return games.save(requested); + }); + Version version = + write.execute( + status -> { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + Version created = versions.save(requested); + sources + .readGenesis(target(created)) + .orElseThrow( + () -> new IllegalStateException("fresh Version lacks actual source genesis")); + return created; + }); + TargetProof target = target(version); + var baseline = + isolatedPolicyBaseline + ? write.execute(status -> baseline(target, dsl, sources, "World")) + : null; + var publicationWrites = new RealmPolicyPublicationRepository(dsl); + var publicationReads = new RealmPolicyPublicationService(publicationWrites, transactions); + return new Fixture( + dsl, + write, + transactions, + target, + baseline, + versions, + new PublishAttemptRepository(dsl), + new PublishedReleaseBundleRepository(dsl), + new GameDesignPublicationOperationRepository(dsl), + policySource, + publicationWrites, + publicationReads); + } + + private static void migrate(DriverManagerDataSource source, String schema) { + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); + } + + private static DraftCommitBinding baseline( + TargetProof target, + DSLContext dsl, + GameDesignSourceRepository sources, + String worldDisplayName) { + SourceHead head = currentSourceHead(target, dsl, sources); + DraftCommitBinding binding = + policyBinding(target, head.baseReference(), head.sourceEpoch(), worldDisplayName); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var reviewed = + new GameDesignReviewedBaseRepository(dsl) + .resolve(target, DraftBaseReference.parse(binding.baseCommitId())); + sources.claimReviewed(binding, reviewed); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + dsl, binding, List.of(applied.ownerOutcome())); + coordinator.releaseApplicationSlot(binding); + return binding; + } + + private static DraftCommitBinding policyBinding( + TargetProof target, String baseReference, String expectedEpoch, String worldDisplayName) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"" + + worldDisplayName + + "\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"isolated-main\",\"policy\":" + + policy.canonicalJson() + + "}"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + baseReference, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch))); + } + + private static SourceHead currentSourceHead( + TargetProof target, DSLContext dsl, GameDesignSourceRepository sources) { + var row = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT source_epoch, visible_commit_id, genesis_receipt_id " + + "FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()), + "fresh Draft fixture must retain its actual policy source head"); + UUID visibleCommit = row.get("visible_commit_id", UUID.class); + UUID genesisReceipt = row.get("genesis_receipt_id", UUID.class); + UUID sharedGenesisReceipt = + sources + .readGenesis(target) + .orElseThrow( + () -> new IllegalStateException("fresh Draft fixture lacks shared genesis")) + .policy() + .receiptId(); + if (!sharedGenesisReceipt.equals(genesisReceipt)) { + throw new IllegalStateException("policy source head differs from shared genesis receipt"); + } + String baseReference = + visibleCommit == null ? "genesis:" + sharedGenesisReceipt : visibleCommit.toString(); + return new SourceHead(row.get("source_epoch", String.class), baseReference); + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private record SourceHead(String sourceEpoch, String baseReference) {} + + private static void assertRejectedHeaderClonesPreserveOriginal( + Fixture fixture, RealmPolicyPublishedEvidence.PublishedSet original) { + String targetProofError = "published realm policy set requires a closed complete TargetProof"; + String terminalBindingError = + "published realm policy set is not bound to exact sealed operation, capture, source, and release"; + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "jsonb_set(existing.target_proof_json::JSONB, '{sourceGameRowId}', 'null'::JSONB)::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "(existing.target_proof_json::JSONB - 'canonicalVersionId')::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "(existing.target_proof_json::JSONB || '{\"unknown\":\"x\"}'::JSONB)::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "operation_bytes", + "existing.operation_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "terminal_evidence_bytes", + "existing.terminal_evidence_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "capture_bytes", + "existing.capture_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "publish_workflow_id", + "('wrong-' || existing.publish_workflow_id)::VARCHAR(1024)", + "published realm policy set operation is unavailable"); + } + + private static void assertRejectedHeaderClonePreservesOriginal( + Fixture fixture, + RealmPolicyPublishedEvidence.PublishedSet original, + String replacementColumn, + String replacementExpression, + String expectedGuardMessage) { + String headerBefore = publishedSetRowJson(fixture); + List policiesBefore = publishedPolicyRowsJson(fixture); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))) + .isEqualTo(original.policyCount()); + + String sql = headerCloneInsertSql(replacementColumn, replacementExpression); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture + .dsl() + .execute( + sql, + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return null; + })) + .satisfies( + failure -> assertThat(rootCause(failure).getMessage()).contains(expectedGuardMessage)); + + assertThat(publishedSetRowJson(fixture)).isEqualTo(headerBefore); + assertThat(publishedPolicyRowsJson(fixture)).containsExactlyElementsOf(policiesBefore); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))) + .isEqualTo(original.policyCount()); + assertPublishedSetUnchanged( + original, fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow()); + } + + private static String headerCloneInsertSql( + String replacementColumn, String replacementExpression) { + if (!PUBLISHED_SET_COLUMNS.contains(replacementColumn)) { + throw new IllegalArgumentException("Published-set clone column is not allowlisted"); + } + String columnList = String.join(", ", PUBLISHED_SET_COLUMNS); + String selectList = + PUBLISHED_SET_COLUMNS.stream() + .map( + column -> { + if ("sealed".equals(column)) return "FALSE"; + if (column.equals(replacementColumn)) return replacementExpression; + return "existing." + column; + }) + .collect(java.util.stream.Collectors.joining(", ")); + return "INSERT INTO game_design_published_realm_policy_set (" + + columnList + + ") SELECT " + + selectList + + " FROM game_design_published_realm_policy_set existing " + + "WHERE existing.canonical_tenant_id = ? AND existing.canonical_version_id = ?"; + } + + private static String publishedSetRowJson(Fixture fixture) { + var row = + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(s)::TEXT AS evidence FROM game_design_published_realm_policy_set s " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + assertThat(row).isNotNull(); + return row.get("evidence", String.class); + } + + private static List publishedPolicyRowsJson(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT to_jsonb(p)::TEXT AS evidence FROM game_design_published_realm_policy p " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? ORDER BY ordinal", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()) + .stream() + .map(row -> row.get("evidence", String.class)) + .toList(); + } + + private static Throwable rootCause(Throwable failure) { + Throwable cause = failure; + while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause(); + return cause; + } + + private static void assertPublishedSetUnchanged( + RealmPolicyPublishedEvidence.PublishedSet expected, + RealmPolicyPublishedEvidence.PublishedSet actual) { + assertThat(actual.target()).isEqualTo(expected.target()); + assertThat(actual.versionNumber()).isEqualTo(expected.versionNumber()); + assertThat(actual.sourceCommitId()).isEqualTo(expected.sourceCommitId()); + assertThat(actual.sourceEpoch()).isEqualTo(expected.sourceEpoch()); + assertThat(actual.publishedReleaseBundleRef()).isEqualTo(expected.publishedReleaseBundleRef()); + assertThat(actual.publishedReleaseBundleDigest()) + .isEqualTo(expected.publishedReleaseBundleDigest()); + assertThat(actual.publishWorkflowId()).isEqualTo(expected.publishWorkflowId()); + assertThat(actual.manifestHash()).isEqualTo(expected.manifestHash()); + assertThat(actual.publicationVersionStateEpoch()) + .isEqualTo(expected.publicationVersionStateEpoch()); + assertThat(actual.operationBytes()).containsExactly(expected.operationBytes()); + assertThat(actual.captureBytes()).containsExactly(expected.captureBytes()); + assertThat(actual.terminalEvidenceBytes()).containsExactly(expected.terminalEvidenceBytes()); + assertThat(actual.policyCount()).isEqualTo(expected.policyCount()); + assertThat(actual.policySetDigest()).isEqualTo(expected.policySetDigest()); + assertThat(actual.policies()).containsExactlyElementsOf(expected.policies()); + } + + private static PublishedReleaseBundle bundle(GameDesignPublicationOperation operation) + throws Exception { + var bundle = new PublishedReleaseBundle(); + bundle.setTenantId(operation.tenantKey()); + bundle.setVersionId(operation.versionId()); + bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(operation.account().tenantId()); + bundle.setCanonicalVersionId(operation.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(operation.workflowId()); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + bundle.setGenerationConfigRevision("generation-isolated-1"); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants( + operation.versionId(), + operation.world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + DataSourceTransactionManager transactions, + TargetProof target, + DraftCommitBinding baseline, + VersionRepository versions, + PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, + GameDesignPublicationOperationRepository operations, + RealmPolicySourceRepository policySource, + RealmPolicyPublicationRepository publicationWrites, + RealmPolicyPublicationService publicationReads) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + + GameDesignPublicationOperation prepare(boolean capturePolicySource) throws Exception { + return tx( + () -> { + try { + var sources = new GameDesignSourceRepository(dsl); + String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked( + dsl, + target, + 1, + "ISOLATED remote owner transaction proof", + sourceBaseReference); + if (capturePolicySource) { + sources.freeze(operation); + } + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + void writePublish(GameDesignPublicationOperation operation, boolean rollBack) throws Exception { + write.executeWithoutResult( + status -> { + try { + IsolatedPublicationOwnerSetup.commitStorage( + dsl, versions, operation, () -> saveBundle(operation)); + if (rollBack) status.setRollbackOnly(); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + PublishedReleaseBundle saveBundle(GameDesignPublicationOperation operation) { + try { + return releases.save(bundle(operation)); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + void moveVersion(VersionLifecycleState next, long epoch) { + tx( + () -> { + var version = + versions + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + version.setVersionState(next); + version.setVersionStateEpoch(epoch); + versions.save(version); + return null; + }); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java index dff00c3c72..b22e55d32c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -50,14 +50,20 @@ void stopPostgres() { void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws Exception { String schema = newSchema("fresh"); DriverManagerDataSource dataSource = dataSource(schema); - migrate(dataSource, schema, null); + // Exercise the selected-schema guard before V50 requires an operation-backed release insert. + migrate(dataSource, schema, MigrationVersion.fromVersion("49.1")); JdbcTemplate jdbc = new JdbcTemplate(dataSource); PersistedTarget accepted = persistTarget(jdbc, 1); WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); - insertRelease( - jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + long acceptedReleaseId = + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + String acceptedRowBeforeLatest = retainedBundleRow(jdbc, acceptedReleaseId); + Map functionBeforeLatest = selectorFunctionIdentity(jdbc); + Map triggerBeforeLatest = selectorTriggerIdentity(jdbc); + String functionBodyBeforeLatest = selectorFunctionBody(jdbc); PersistedTarget rejected = persistTarget(jdbc, 2); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); @@ -79,6 +85,14 @@ void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws E .isEqualTo("release v2 participant differs from selected commit/digest/schema"); }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + + migrate(dataSource, schema, null); + + assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); + assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBeforeLatest); + assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBeforeLatest); + assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyBeforeLatest); + assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 3); } @Test @@ -106,7 +120,7 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() String functionBodyBefore = selectorFunctionBody(jdbc); assertThat(functionBodyBefore).contains("('GAME_DESIGN_CONTROL_PLANE',1)"); - migrate(dataSource, schema, null); + migrate(dataSource, schema, MigrationVersion.fromVersion("49.1")); assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); assertThat(retainedBundleRow(jdbc, legacyV2BundleId)).isEqualTo(legacyV2RowBefore); @@ -119,9 +133,11 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() PersistedTarget accepted = persistTarget(jdbc, 2); WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); - insertRelease( - jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + long acceptedReleaseId = + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + String acceptedRowBeforeLatest = retainedBundleRow(jdbc, acceptedReleaseId); PersistedTarget rejected = persistTarget(jdbc, 3); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); @@ -143,6 +159,32 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() .isEqualTo("release v2 participant differs from selected commit/digest/schema"); }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + + String functionBodyAfterSelectorMigration = selectorFunctionBody(jdbc); + migrate(dataSource, schema, null); + + assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); + assertThat(retainedBundleRow(jdbc, legacyV2BundleId)).isEqualTo(legacyV2RowBefore); + assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); + assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBefore); + assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBefore); + assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyAfterSelectorMigration); + assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 4); + } + + private void assertLatestGuardRejectsReleaseWithoutOwnerAttempt( + JdbcTemplate jdbc, int versionNumber) throws Exception { + // A schema-valid v2 row still needs a genuine publication attempt under the latest guard. + PersistedTarget target = persistTarget(jdbc, versionNumber); + WorldPublishedStartLocationEvidence targetEvidence = evidence(target); + assertThatThrownBy( + () -> + insertRelease( + jdbc, target, targetEvidence, selectedV2Participants(target, targetEvidence))) + .rootCause() + .isInstanceOf(PSQLException.class) + .satisfies(cause -> assertThat(((PSQLException) cause).getSQLState()).isEqualTo("P0002")); + assertThat(releaseCount(jdbc, target.versionId())).isEqualTo(0L); } private DriverManagerDataSource dataSource(String schema) { 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 aa3100afe8..19bbf05c41 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 @@ -12,13 +12,19 @@ import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; -import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +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.GameAsset; @@ -33,6 +39,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; @@ -41,11 +48,14 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -56,12 +66,17 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.util.AopTestUtils; +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.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** - * PostgreSQL proof for asset publication boundaries, transaction behavior, and failure retention. + * PostgreSQL proof for isolated selected-publication mechanics, finalization recovery, and + * public-ingress denial. */ @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -82,6 +97,7 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String FIXTURE_PUBLIC_BASE_URL = "https://assets.example.test/assets"; private static final String ARTIFACT_DIGEST = "sha256:6eb74f970ab34ad786c5089af8780d7a218f91f9d6a7ed03675185e39b317e94"; private static final byte[] FIXTURE_ASSET_BYTES = @@ -100,21 +116,38 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private GameRepository gameRepository; @Autowired private GameAssetRepository gameAssetRepository; @Autowired private PublishAttemptServiceImpl publishAttemptService; + @Autowired private VersionServiceImpl versionService; @Autowired private VersionPublishCommandServiceImpl versionPublishCommandService; - @Autowired private VersionService versionService; @Autowired private PublishAttemptRepository publishAttemptRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; - @Autowired private VersionAssetPublicationService versionAssetPublicationService; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; @Autowired private VersionAssetExportCandidateService exportCandidateService; + @Autowired private VersionAssetPublicationService versionAssetPublicationService; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private ControlPlaneDigestService controlPlaneDigestService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; + @Test + void fullVersionSealTransactionUsesExplicitReadCommittedIsolation() { + AtomicReference isolation = new AtomicReference<>(); + + publishAttemptService.executeFullVersionTransaction( + () -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + isolation.set(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + return null; + }); + + assertThat(isolation.get()).isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + @Test void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { Game game = new Game(); @@ -184,6 +217,84 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { assertThat(gameRepository.findByTenantId(TENANT_ID)).isNotNull(); } + @Test + void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { + String tenantId = isolatedTenantId(); + long baseVersionId = + createGameAndPublishedBaseVersion(tenantId, "script-patch-failure-replay-game"); + String scriptPatchVersion = "patch-failed-replay"; + String publishRequestId = "script-patch-failure-replay"; + String workflowId = + PublicationDigestRequestBinding.patch( + tenantId, String.valueOf(baseVersionId), scriptPatchVersion, publishRequestId) + .derivedWorkflowIdentity(); + Game savedGame = gameRepository.findByTenantId(tenantId); + + Mockito.doThrow(new IllegalStateException("script patch participant unavailable")) + .when(publishGateService) + .collectScriptPatchParticipantDigests( + Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(workflowId)); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "first notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + PublishAttempt failedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(failedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(failedAttempt.getFailureCode()).isEqualTo("PUBLISH_FAILED"); + assertThat(failedAttempt.getFailureMessage()).isEqualTo("script patch participant unavailable"); + Version retainedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + assertThat(retainedVersion.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(retainedVersion.getVersionStateEpoch()).isEqualTo(1L); + assertThat(retainedVersion.getCanonicalVersionId()).isNotNull(); + assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(savedGame.getCanonicalTenantId()); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "changed notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + Version replayedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + PublishAttempt replayedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(replayedVersion.getId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedVersion.getCanonicalVersionId()) + .isEqualTo(retainedVersion.getCanonicalVersionId()); + assertThat(replayedVersion.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(replayedVersion.getVersionStateEpoch()).isEqualTo(1L); + assertThat(replayedAttempt.getVersionId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "new identity", "new-request-id")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); + assertThat( + versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion)) + .hasSize(1); + } + @Test void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { String tenantId = "9011"; @@ -435,75 +546,16 @@ void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed } @Test - void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() { - String tenantId = "9004"; - String publishWorkflowId = "full-version-digest-backfill-integration-test"; - Game game = new Game(); - game.setTenantId(tenantId); - game.setName("digest-backfill-proof-game"); - gameRepository.save(game); - - Version version = new Version(); - version.setTenantId(tenantId); - version.setVersionNumber(1); - version.setVersionState(VersionLifecycleState.DRAFT); - version.setVersionStateEpoch(1L); - version.setNotes("digest backfill proof"); - Version savedVersion = versionRepository.save(version); - - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId(tenantId); - attempt.setPublishWorkflowId(publishWorkflowId); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setStatus(PublishAttemptStatus.PENDING); - attempt.setVersionId(savedVersion.getId()); - attempt.setVersionNumber(savedVersion.getVersionNumber()); - publishAttemptRepository.save(attempt); - PublishAttempt savedAttempt = - publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); - - PublishAttempt backfilled = - publishAttemptRepository - .backfillFullVersionRequestDigestIfAbsent( - savedAttempt.getId(), - tenantId, - publishWorkflowId, - savedVersion.getId(), - savedVersion.getVersionNumber(), - "exact-identity-digest") - .orElseThrow(); - - assertThat(backfilled.getRequestDigest()).isEqualTo("exact-identity-digest"); - assertThat( - publishAttemptRepository.backfillFullVersionRequestDigestIfAbsent( - savedAttempt.getId(), - "wrong-tenant", - publishWorkflowId, - savedVersion.getId(), - savedVersion.getVersionNumber(), - "mismatched-identity-digest")) - .isEmpty(); - PublishAttempt storedAttempt = - publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); - assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); - } - - // An exact candidate without its bundle is partial evidence and must remain pending. - @Test - void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { - 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); - AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); + void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { + String tenantId = isolatedTenantId(); + SelectedPublicationFixture fixture = + selectedPublicationFixture(tenantId, "pending-readback-proof-game", false); + String publishRequestId = + fixture.operation().account().input().selection().intent().publishRequestId(); + String publishWorkflowId = fixture.operation().workflowId(); + ExportedAssetManifest candidate = recordFixtureCandidate(fixture); + AtomicReference recordedDigestFailure = new AtomicReference<>(); + AtomicInteger artifactReadbackCount = new AtomicInteger(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -512,26 +564,60 @@ void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { - VersionDto version = invocation.getArgument(0); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(version.id()), - "version:" + version.id(), - "transaction-proof-design-digest", - 1, - null, - null)); + VersionDto selectedVersion = invocation.getArgument(0); + return PublishedWorldSelectorFixtures.participants( + selectedVersion.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); }); - Mockito.when(assetExportService.exportAssets(tenantId, 1)) - .thenAnswer(invocation -> recordFixtureCandidate(tenantId, invocation.getArgument(1))); + Mockito.doAnswer( + invocation -> { + try { + invocation.callRealMethod(); + } catch (Throwable failure) { + recordedDigestFailure.set(failure); + throw failure; + } + return null; + }) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); + Mockito.doAnswer( + invocation -> { + int readbackNumber = artifactReadbackCount.incrementAndGet(); + Object actualReadback = invocation.callRealMethod(); + if (readbackNumber != 2 + || !(actualReadback instanceof Optional actualState) + || actualState.isEmpty()) { + return actualReadback; + } + VersionAssetArtifactStateDto actual = + (VersionAssetArtifactStateDto) actualState.orElseThrow(); + return Optional.of( + new VersionAssetArtifactStateDto( + actual.tenantId(), + actual.versionId(), + actual.exportedVersionNumber(), + actual.artifactState(), + actual.stateEpoch(), + actual.manifestHash(), + actual.lastWorkflowId() + "-unconfirmed", + actual.lastErrorCode(), + actual.lastErrorMessage(), + actual.updatedAt(), + actual.exportedManifestAssetKeys())); + }) + .when(versionAssetArtifactService) + .findState(Mockito.eq(tenantId), Mockito.eq(fixture.version().getId())); + Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) + .thenAnswer(invocation -> candidate); Throwable reconciliationFailure = - catchThrowable( - () -> - reconcileFullVersionPublishMechanics( - tenantId, "successful transaction proof", publishRequestId, publishWorkflowId)); - assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); + catchThrowable(() -> reconcileSelectedPublicationMechanics(fixture)); + assertThat(recordedDigestFailure.get()).isNull(); + assertThat(artifactReadbackCount.get()).isEqualTo(2); + assertThat(reconciliationFailure) .isInstanceOf(IllegalStateException.class) .hasMessage( @@ -540,32 +626,30 @@ void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { .isEqualTo( "net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl" + "$PendingReconciliationException"); - PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); - Version storedVersion = - versionRepository.findByTenantIdAndId(tenantId, attempt.getVersionId()).orElseThrow(); + Version retainedDraft = + versionRepository.findByTenantIdAndId(tenantId, fixture.version().getId()).orElseThrow(); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); assertThat(attempt.getFailureCode()).isNull(); assertThat(attempt.getFailureMessage()).isNull(); - assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); - assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(retainedDraft.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); assertThat( publishedReleaseBundleRepository.findByTenantIdAndVersionId( - tenantId, attempt.getVersionId())) + tenantId, retainedDraft.getId())) .isEmpty(); - VersionAssetArtifact artifact = + VersionAssetArtifact storedArtifact = versionAssetArtifactRepository - .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) + .findByTenantIdAndVersionId(tenantId, retainedDraft.getId()) .orElseThrow(); - assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); - assertThat(artifact.getLastErrorCode()).isNull(); - assertThat(artifact.getLastErrorMessage()).isNull(); - assertThat( - exportCandidateService - .readExportCandidate(tenantId, storedVersion.getVersionNumber()) - .manifest()) - .isEqualTo(exportedManifest()); + assertThat(storedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); + assertThat(storedArtifact.getLastWorkflowId()).isEqualTo(publishWorkflowId); + FrozenAssetExportCandidate retainedCandidate = + exportCandidateService.readExportCandidate(tenantId, retainedDraft.getVersionNumber()); + assertThat(retainedCandidate) + .isEqualTo(new FrozenAssetExportCandidate(candidate, FIXTURE_PUBLIC_BASE_URL)); + Mockito.verify(assetExportService) + .exportAssets(Mockito.eq(tenantId), Mockito.eq(fixture.version().getVersionNumber())); Mockito.verify(versionAssetArtifactService, Mockito.never()) .markPublished( Mockito.eq(tenantId), @@ -576,28 +660,17 @@ void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { } @Test - void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailable() { - 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.setName("failed-remap-proof-game"); - gameRepository.save(game); - - Version sourceVersion = new Version(); - sourceVersion.setTenantId(tenantId); - sourceVersion.setVersionNumber(1); - sourceVersion.setVersionState(VersionLifecycleState.PUBLISHED); - sourceVersion.setVersionStateEpoch(2L); - sourceVersion.setNotes("remap source"); - sourceVersion = versionRepository.save(sourceVersion); + void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() { + String tenantId = isolatedTenantId(); + SelectedPublicationFixture fixture = + selectedPublicationFixture(tenantId, "failed-remap-proof-game", true); + String publishRequestId = + fixture.operation().account().input().selection().intent().publishRequestId(); + String publishWorkflowId = fixture.operation().workflowId(); + Version sourceVersion = + versionRepository.findByTenantIdAndVersionNumber(tenantId, 1).orElseThrow(); long sourceVersionId = sourceVersion.getId(); + String approvedRemapSetId = "failed-remap-" + UUID.randomUUID(); AtomicReference candidateVersionId = new AtomicReference<>(); AtomicReference candidateVersionNumber = new AtomicReference<>(); AtomicReference exportedVersionNumber = new AtomicReference<>(); @@ -606,6 +679,7 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab AtomicReference exportCallbackFailure = new AtomicReference<>(); AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); AtomicBoolean exportCompleted = new AtomicBoolean(); + AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -617,15 +691,10 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab VersionDto candidate = invocation.getArgument(0); candidateVersionId.set(candidate.id()); candidateVersionNumber.set(candidate.versionNumber()); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(candidate.id()), - "version:" + candidate.id(), - "failed-remap-design-digest", - 1, - null, - null)); + return PublishedWorldSelectorFixtures.participants( + candidate.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { @@ -647,7 +716,7 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab exportedVersionNumber.set(invocation.getArgument(1)); try { VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); - approvedRemapSet.setRemapSetId("failed-candidate-approved-remap"); + approvedRemapSet.setRemapSetId(approvedRemapSetId); approvedRemapSet.setTenantId(tenantId); approvedRemapSet.setSourceVersionId(sourceVersionId); approvedRemapSet.setTargetVersionId(candidateVersionId.get()); @@ -659,34 +728,57 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab templateRemapSetRepository.save(approvedRemapSet); remapSetId.set(approvedRemapSet.getRemapSetId()); exportCompleted.set(true); - return recordFixtureCandidate( - tenantId, invocation.getArgument(1), exportedManifest); + return recordFixtureCandidate(fixture, exportedManifest); } catch (Throwable failure) { exportCallbackFailure.set(failure); throw failure; } }); + Mockito.doAnswer( + invocation -> { + finalizationFailureInjected.set(true); + throw new IllegalStateException("forced finalization failure"); + }) + .when(versionAssetArtifactService) + .markPublished( + Mockito.eq(tenantId), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.eq(publishWorkflowId), + Mockito.eq(exportedManifest.manifestHash())); + Throwable reconciliationFailure = - catchThrowable( - () -> - reconcileFullVersionPublishMechanics( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)); + catchThrowable(() -> reconcileSelectedPublicationMechanics(fixture)); assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); - assertThat(recordedDigestFailure.get()).isNull(); - assertThat(exportCallbackFailure.get()).isNull(); assertThat(reconciliationFailure) .isInstanceOf(IllegalStateException.class) - .hasMessage( - "published release evidence is incomplete; readback/reconciliation is required"); - assertThat(reconciliationFailure.getClass().getName()) - .isEqualTo( - "net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl" - + "$PendingReconciliationException"); + .hasMessage("exported candidate requires exact retry/reconciliation"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); - assertThat(exportCompleted.get()) - .as("asset export candidate capture completes before finalization readback") - .isTrue(); + String reconciliationContext = + "mechanics reconciliation context (candidateVersionId=" + + candidateVersionId.get() + + ", candidateVersionNumber=" + + candidateVersionNumber.get() + + ", exportedVersionNumber=" + + exportedVersionNumber.get() + + ", attemptStatus=" + + attempt.getStatus() + + ", attemptFailureCode=" + + attempt.getFailureCode() + + ", attemptFailureMessage=" + + attempt.getFailureMessage() + + ", recordedDigestFailure=" + + recordedDigestFailure.get() + + ", exportCallbackFailure=" + + exportCallbackFailure.get() + + ", exportCallbackFailureFrame=" + + firstStackFrame(exportCallbackFailure.get()) + + ", reconciliationFailure=" + + reconciliationFailure + + ")"; + assertThat(exportCompleted.get()).as(reconciliationContext).isTrue(); + assertThat(finalizationFailureInjected.get()).as(reconciliationContext).isTrue(); assertThat(exportedVersionNumber.get()) .as("asset export uses the candidate's persisted version number") .isEqualTo(candidateVersionNumber.get()); @@ -696,42 +788,46 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab Version retainedCandidate = versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(retainedCandidate.getVersionStateEpoch()) + .isEqualTo( + Long.parseLong( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .expectedVersionStateEpoch())); assertThat( publishedReleaseBundleRepository.findByTenantIdAndVersionId( tenantId, candidateVersionId.get())) .isEmpty(); - VersionAssetArtifact failedArtifact = + VersionAssetArtifact retainedArtifact = versionAssetArtifactRepository .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) .orElseThrow(); - assertThat(failedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); - assertThat(failedArtifact.getLastErrorCode()).isNull(); - assertThat(failedArtifact.getLastErrorMessage()).isNull(); - FrozenAssetExportCandidate retainedExportCandidate = - exportCandidateService.readExportCandidate(tenantId, retainedCandidate.getVersionNumber()); - assertThat(retainedExportCandidate) - .isEqualTo( - new FrozenAssetExportCandidate(exportedManifest, "https://assets.example.test/assets")); + assertThat(retainedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); + FrozenAssetExportCandidate expectedCandidate = + new FrozenAssetExportCandidate(exportedManifest, FIXTURE_PUBLIC_BASE_URL); + assertThat( + exportCandidateService.readExportCandidate( + tenantId, retainedCandidate.getVersionNumber())) + .isEqualTo(expectedCandidate); assertThat( exportCandidateService.recordExportCandidate( - tenantId, retainedCandidate.getVersionNumber(), retainedExportCandidate)) - .isEqualTo(retainedExportCandidate); - assertThatThrownBy( - () -> - exportCandidateService.recordExportCandidate( - tenantId, - retainedCandidate.getVersionNumber(), - new FrozenAssetExportCandidate( - exportedManifest, "https://changed-origin.example.test/assets"))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + tenantId, retainedCandidate.getVersionNumber(), expectedCandidate)) + .isEqualTo(expectedCandidate); Mockito.verify(versionAssetArtifactService, Mockito.never()) - .markPublished( + .markFailed( Mockito.eq(tenantId), - Mockito.anyLong(), - Mockito.anyLong(), + Mockito.eq(candidateVersionId.get()), + Mockito.eq(candidateVersionNumber.get()), Mockito.eq(publishWorkflowId), + Mockito.any(ExportedAssetManifest.class), + Mockito.anyString(), Mockito.anyString()); + Mockito.verify(assetExportService, Mockito.never()) + .deleteExportedAssets(Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) @@ -742,6 +838,59 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); } + // These private mechanics tests use isolated Account/World fixture evidence. They exercise + // selected publication and finalization recovery, not live authorization or ingress. + @Test + void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { + String tenantId = "9002"; + SelectedPublicationFixture fixture = + selectedPublicationFixture(tenantId, "successful-transaction-proof-game", false); + String publishRequestId = + fixture.operation().account().input().selection().intent().publishRequestId(); + String publishWorkflowId = fixture.operation().workflowId(); + AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); + + Mockito.when( + publishGateService.collectFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.eq(publishRequestId), + Mockito.eq(publishWorkflowId))) + .thenAnswer( + invocation -> { + VersionDto version = invocation.getArgument(0); + return PublishedWorldSelectorFixtures.participants( + version.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + }); + Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) + .thenAnswer(invocation -> recordFixtureCandidate(fixture)); + + Object snapshot = reconcileSelectedPublicationMechanics(fixture); + assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); + assertMechanicsSnapshot(snapshot, "SUCCEEDED", ""); + + PublishAttempt attempt = + publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); + Version storedVersion = + versionRepository.findByTenantIdAndId(tenantId, fixture.version().getId()).orElseThrow(); + PublishedReleaseBundle bundle = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) + .orElseThrow(); + VersionAssetArtifact artifact = + versionAssetArtifactRepository + .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) + .orElseThrow(); + + assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); + assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); + assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); + assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); + assertThat(bundle.getManifestHash()).isEqualTo(MANIFEST_HASH); + assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); + } + @Test void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { String freshTenantId = "9010"; @@ -767,7 +916,7 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { assertThat(publishAttemptRepository.findByPublishWorkflowId(freshWorkflowId)).isEmpty(); assertThat(versionRepository.findByTenantIdAndVersionNumber(freshTenantId, 1)).isEmpty(); - String pendingTenantId = "9013"; + String pendingTenantId = isolatedTenantId(); String pendingRequestId = "pending-public-denial"; String pendingWorkflowId = FiremudWorkflowIds.workflowId( @@ -823,21 +972,86 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { Mockito.verifyNoInteractions(assetExportService); } - /** Exercises the private transaction mechanics only; this is not production ingress proof. */ - private Object reconcileFullVersionPublishMechanics( - String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + /** Fixture-only Account/World inputs; this exercises GD's actual selected owner transaction. */ + private SelectedPublicationFixture selectedPublicationFixture( + String tenantId, String gameName, boolean includePublishedSource) { + TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager); + sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return sourceTransaction.execute( + status -> { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName(gameName); + gameRepository.save(game); + + if (includePublishedSource) { + Version source = new Version(); + source.setTenantId(tenantId); + source.setVersionNumber(1); + source.setVersionState(VersionLifecycleState.PUBLISHED); + source.setVersionStateEpoch(2L); + source.setNotes("ISOLATED remap source"); + versionRepository.save(source); + } + + Version draft = new Version(); + draft.setTenantId(tenantId); + draft.setVersionNumber(includePublishedSource ? 2 : 1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("ISOLATED selected publication"); + Version persisted = versionRepository.save(draft); + TargetProof target = + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind()); + try { + GameDesignPublicationOperation operation = + IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, target, persisted.getVersionStateEpoch(), "ISOLATED publication proof"); + return new SelectedPublicationFixture(persisted, operation); + } catch (Exception failure) { + throw new IllegalStateException("Selected publication fixture setup failed", failure); + } + }); + } + + private Object reconcileSelectedPublicationMechanics(SelectedPublicationFixture fixture) { try { Class requestType = Class.forName("net.firedevops.firemud.gamedesign.service.impl.PublishWorkflowRequest"); + var selected = fixture.operation().account().input().selection(); + var selectedIntent = selected.intent(); + var selectedCommit = selected.selectedCommit(); + PublishIntent intent = + new PublishIntent( + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + selectedIntent.publishRequestId(), + selectedIntent.expectedVersionStateEpoch(), + selectedIntent.notes(), + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); Constructor requestConstructor = requestType.getDeclaredConstructor( - String.class, String.class, String.class, String.class); + String.class, String.class, String.class, String.class, PublishIntent.class); requestConstructor.setAccessible(true); Object request = - requestConstructor.newInstance(tenantId, notes, publishRequestId, publishWorkflowId); + requestConstructor.newInstance( + fixture.version().getTenantId(), + selectedIntent.notes(), + selectedIntent.publishRequestId(), + fixture.operation().workflowId(), + intent); Method mechanics = VersionPublishCommandServiceImpl.class.getDeclaredMethod( - "reconcileFullVersionPublishMechanics", requestType); + "reconcileSelectedPublicationMechanics", requestType); mechanics.setAccessible(true); Object target = AopTestUtils.getTargetObject(versionPublishCommandService); return mechanics.invoke(target, request); @@ -855,6 +1069,56 @@ private Object reconcileFullVersionPublishMechanics( } } + private ExportedAssetManifest recordFixtureCandidate(SelectedPublicationFixture fixture) { + return recordFixtureCandidate(fixture, exportedManifest()); + } + + private ExportedAssetManifest recordFixtureCandidate( + SelectedPublicationFixture fixture, ExportedAssetManifest candidate) { + String tenantId = fixture.version().getTenantId(); + int versionNumber = fixture.version().getVersionNumber(); + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Fixture Version was not persisted")); + versionAssetArtifactService.stageExport( + tenantId, version.getId(), versionNumber, fixture.operation().workflowId()); + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName("fixture.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(FIXTURE_ASSET_BYTES); + GameAsset persistedAsset = gameAssetRepository.save(asset); + versionAssetPublicationService.associateDraftAsset( + tenantId, version.getId(), persistedAsset.getId(), "fixture.bin"); + versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); + FrozenAssetExportCandidate frozenCandidate = + exportCandidateService.recordExportCandidate( + tenantId, + versionNumber, + new FrozenAssetExportCandidate(candidate, FIXTURE_PUBLIC_BASE_URL)); + return frozenCandidate.manifest(); + } + + private record SelectedPublicationFixture( + Version version, GameDesignPublicationOperation operation) {} + + private static void assertMechanicsSnapshot( + Object snapshot, String expectedStatus, String expectedFailureMessage) { + String actualStatus = snapshotValue(snapshot, "status"); + String actualFailureCode = snapshotValue(snapshot, "failureCode"); + String actualFailureMessage = snapshotValue(snapshot, "failureMessage"); + String failureContext = + "publication mechanics snapshot: status=" + + actualStatus + + ", failureCode=" + + actualFailureCode + + ", failureMessage=" + + actualFailureMessage; + assertThat(actualStatus).as(failureContext).isEqualTo(expectedStatus); + assertThat(actualFailureMessage).as(failureContext).isEqualTo(expectedFailureMessage); + } + private AtomicReference captureControlPlaneDigestFailure() { AtomicReference failure = new AtomicReference<>(); Mockito.doAnswer( @@ -880,6 +1144,25 @@ private static void assertNoControlPlaneDigestFailure(Throwable failure) { assertThat(failure).as("real control-plane digest computation failed:\n" + stackTrace).isNull(); } + private static String snapshotValue(Object snapshot, String accessorName) { + try { + Method accessor = snapshot.getClass().getDeclaredMethod(accessorName); + accessor.setAccessible(true); + return (String) accessor.invoke(snapshot); + } catch (InvocationTargetException exception) { + throw new AssertionError("publication snapshot accessor failed", exception.getCause()); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("publication snapshot accessor is unavailable", exception); + } + } + + private static String firstStackFrame(Throwable failure) { + if (failure == null || failure.getStackTrace().length == 0) { + return "none"; + } + return failure.getStackTrace()[0].toString(); + } + private static ExportedAssetManifest exportedManifest() { return new ExportedAssetManifest( MANIFEST_HASH, @@ -895,33 +1178,6 @@ private static ExportedAssetManifest exportedManifest() { 1))); } - private ExportedAssetManifest recordFixtureCandidate(String tenantId, int versionNumber) { - return recordFixtureCandidate(tenantId, versionNumber, exportedManifest()); - } - - private ExportedAssetManifest recordFixtureCandidate( - String tenantId, int versionNumber, ExportedAssetManifest candidate) { - Version version = - versionRepository - .findByTenantIdAndVersionNumber(tenantId, versionNumber) - .orElseThrow(() -> new IllegalStateException("Fixture Version was not persisted")); - GameAsset asset = new GameAsset(); - asset.setTenantId(tenantId); - asset.setFileName("fixture.bin"); - asset.setContentType("application/octet-stream"); - asset.setData(FIXTURE_ASSET_BYTES); - GameAsset persistedAsset = gameAssetRepository.save(asset); - versionAssetPublicationService.associateDraftAsset( - tenantId, version.getId(), persistedAsset.getId(), "fixture.bin"); - versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); - return exportCandidateService - .recordExportCandidate( - tenantId, - versionNumber, - new FrozenAssetExportCandidate(candidate, "https://assets.example.test/assets")) - .manifest(); - } - private long createGameAndPublishedBaseVersion(String tenantId, String gameName) { Game game = new Game(); game.setTenantId(tenantId); @@ -936,4 +1192,8 @@ private long createGameAndPublishedBaseVersion(String tenantId, String gameName) baseVersion.setNotes("published script patch base"); return versionRepository.save(baseVersion).getId(); } + + private static String isolatedTenantId() { + return Long.toString(UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java new file mode 100644 index 0000000000..4ab73cfb74 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -0,0 +1,99 @@ +package unit.net.firedevops.firemud.gamedesign.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.util.List; +import net.firedevops.firemud.gamedesign.config.RealmPolicyPublicationReadConfiguration; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.io.FileSystemResource; +import org.springframework.transaction.PlatformTransactionManager; + +class RealmPolicyPublicationReadConfigurationTest { + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + RealmPolicyPublicationReadConfiguration.class, + RealmPolicyPublicationGrpcService.class) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withBean(PlatformTransactionManager.class, () -> mock(PlatformTransactionManager.class)); + + @Test + void ownerReadCompositionAndGrpcAdapterAreAbsentByDefault() { + contextRunner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationRepository.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationService.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationGrpcService.class); + }); + } + + @Test + void explicitEnablementComposesActualOwnerBeansAndGrpcAdapter() { + contextRunner + .withPropertyValues( + "firemud.game-design.published-realm-entry-policy-read.enabled=true", + "firemud.grpc.workload-namespace=firemud-test") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(RealmPolicyPublicationRepository.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationService.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationGrpcService.class); + }); + } + + @Test + void enabledCompositionFailsClosedForMissingOrInvalidNamespace() { + contextRunner + .withPropertyValues("firemud.game-design.published-realm-entry-policy-read.enabled=true") + .run(context -> assertThat(context).hasFailed()); + + contextRunner + .withPropertyValues( + "firemud.game-design.published-realm-entry-policy-read.enabled=true", + "firemud.grpc.workload-namespace=Invalid_Namespace") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void baseAndProductionYamlBindOnlyTheExplicitPolicyReadMethods() throws IOException { + assertConfiguredGrpcMethods("application.yml"); + assertConfiguredGrpcMethods("application-prod.yml"); + } + + private static void assertConfiguredGrpcMethods(String fileName) throws IOException { + var propertySources = + new YamlPropertySourceLoader() + .load(fileName, new FileSystemResource("src/main/resources/" + fileName)); + new ApplicationContextRunner() + .withInitializer( + context -> + propertySources.forEach(context.getEnvironment().getPropertySources()::addFirst)) + .run( + context -> + assertThat( + Binder.get(context.getEnvironment()) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())) + .containsExactly( + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + PublishedRealmEntryPolicyServiceGrpc + .getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc + .getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName())); + } +} 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..3663aada47 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -0,0 +1,213 @@ +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.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +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; +import tools.jackson.databind.ObjectMapper; + +class AuthoredDraftPublishSelectionTest { + private static final String LARGE_COUNTER = "900719925474099312345678901234567890"; + + @Test + void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() throws Exception { + 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"); + // Independent original V43 object layout. Extraction must preserve its exact bytes/digest. + byte[] legacy = + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + Map.of( + "schemaVersion", + "1", + "intent", + Map.of( + "canonicalTenantId", + intent.canonicalTenantId().toString(), + "canonicalVersionId", + intent.canonicalVersionId().toString(), + "publishRequestId", + intent.publishRequestId(), + "expectedVersionStateEpoch", + intent.expectedVersionStateEpoch(), + "notes", + intent.notes(), + "selectedCommitRequestId", + intent.selectedCommitRequestId().toString(), + "selectedCommitId", + intent.selectedCommitId().toString(), + "selectedCommitDigest", + intent.selectedCommitDigest()), + "target", + Map.of( + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind()), + "selectedCommitBindingJson", + binding.canonicalJson(), + "selectedCommitDigest", + binding.digest(), + "synchronizedFence", + Map.of( + "requestId", + fence.requestId().toString(), + "commitId", + fence.commitId().toString(), + "inputDigest", + fence.inputDigest(), + "resultVectorJson", + fence.resultVectorJson(), + "createdAt", + "2026-10-05T00:00:00Z")))); + assertThat(selection.canonicalBytes()).containsExactly(legacy); + assertThat(selection.digest()).isEqualTo(DraftAuthorizationFenceBinding.digest(legacy)); + var shared = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + assertThat(shared.canonicalBytes()).containsExactly(legacy); + } + + @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/GameDesignReviewedBaseEvidenceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java new file mode 100644 index 0000000000..78b7d4afa8 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +import org.junit.jupiter.api.Test; + +class GameDesignReviewedBaseEvidenceTest { + @Test + void genesisBindsOriginalPairedReceiptTargetAndCreationWitnessWithoutCommit() { + var target = + new TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 7, "tenant", 3, "tenant", "NEW_GAME_ROW"); + var receipt = UUID.randomUUID(); + var genesis = genesis(target, receipt, "11"); + var evidence = GameDesignReviewedBaseEvidence.genesis(genesis); + assertThat(evidence.target()).isEqualTo(target); + assertThat(evidence.reference()).isEqualTo(DraftBaseReference.parse("genesis:" + receipt)); + assertThat(evidence.canonicalBytes()).contains(genesis.policy().canonicalBytes()); + assertThat(evidence.canonicalBytes()).contains(genesis.command().canonicalBytes()); + assertThat(evidence.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(evidence.canonicalBytes())); + assertThat(evidence).isEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis)); + assertThat(evidence) + .isNotEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis(target, receipt, "12"))); + assertThat(evidence) + .isNotEqualTo( + GameDesignReviewedBaseEvidence.genesis(genesis(target, UUID.randomUUID(), "11"))); + byte[] returned = evidence.canonicalBytes(); + returned[0] ^= 1; + assertThat(returned).isNotEqualTo(evidence.canonicalBytes()); + } + + @Test + void readbackRejectsChangedDigestAndDefensivelyCopiesBytes() { + byte[] bytes = {1, 2, 3}; + var retained = + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + bytes, DraftAuthorizationFenceBinding.digest(bytes)); + bytes[0] = 9; + assertThat(retained.canonicalBytes()).containsExactly(1, 2, 3); + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback(bytes, retained.digest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static GameDesignSourceRepository.Genesis genesis( + TargetProof target, UUID receipt, String witness) { + return new GameDesignSourceRepository.Genesis( + new RealmPolicyGenesis(target, receipt, witness), + new CommandSource.NewDraftGenesisReceipt(target, receipt, witness)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java new file mode 100644 index 0000000000..9a160c7cbf --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -0,0 +1,282 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.publication.CommandApplication; +import net.firedevops.firemud.gamedesign.publication.CommandSnapshot; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import org.junit.jupiter.api.Test; + +class CommandSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 7L, "owner", 3L, "owner", "NEW_GAME_ROW"); + + @Test + void parsesOnlyClosedDigestBoundOperationsAndRetainsExactPayloadAndProvenance() { + String definition = + command("look", "l").replace("{\"schemaVersion\":1", "{ \"schemaVersion\":1"); + UUID commitId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + var binding = + binding( + commitId, + List.of(revision("0", revisionId, CommandSource.upsertPayload(definition))), + List.of(commandScope("0"))); + + var mutation = CommandSource.mutations(binding).getFirst(); + assertThat(mutation.commandId()).isEqualTo("look"); + assertThat(mutation.definitionJson()).isEqualTo(definition); + assertThat(mutation.commitId()).isEqualTo(commitId); + assertThat(mutation.revisionId()).isEqualTo(revisionId); + assertThat(mutation.revisionOrder()).isEqualTo("0"); + + var malformed = + List.of( + Map.entry( + CommandSource.upsertPayload(definition) + .replace("\"operation\":\"UPSERT\"", "\"operation\":\"UPSERT\",\"extra\":true"), + "Closed command source operation fields are required"), + Map.entry( + "{\"schemaVersion\":1,\"revisionKind\":\"UNSUPPORTED\",\"operation\":\"DELETE\",\"commandId\":\"look\"}", + "Unsupported Game Design command source revision kind"), + Map.entry( + CommandSource.upsertPayload(definition) + .replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + "Unsupported command source operation schema")); + for (var malformedCase : malformed) { + var bad = + binding( + commitId, + List.of(revision("0", revisionId, malformedCase.getKey())), + List.of(commandScope("0"))); + assertThatThrownBy(() -> CommandSource.mutations(bad)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(malformedCase.getValue()); + } + } + + @Test + void replaysStableKeyUpsertAndExplicitDeleteInRevisionOrderWithoutLosingAuthorship() { + var inherited = List.of(definition("look", "l", UUID.randomUUID(), UUID.randomUUID(), "0")); + UUID commit = UUID.randomUUID(); + UUID upsertRevision = UUID.randomUUID(); + String exactDefinition = command("LOOK", "see"); + var operations = + List.of( + new CommandSource.Mutation( + "0", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "look", null), + new CommandSource.Mutation( + "1", + upsertRevision, + commit, + CommandSource.OperationKind.UPSERT, + "LOOK", + exactDefinition)); + + var result = CommandSource.replay(inherited, operations); + assertThat(result).hasSize(1); + assertThat(result.getFirst().commandId()).isEqualTo("LOOK"); + assertThat(result.getFirst().definitionJson()).isEqualTo(exactDefinition); + assertThat(result.getFirst().sourceCommitId()).isEqualTo(commit); + assertThat(result.getFirst().sourceRevisionId()).isEqualTo(upsertRevision); + assertThat(CommandSource.replay(inherited, List.of())).containsExactlyElementsOf(inherited); + var delete = + new CommandSource.Mutation( + "2", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "LOOK", null); + assertThat(CommandSource.replay(result, List.of(delete))).isEmpty(); + var absentDelete = + new CommandSource.Mutation( + "3", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "absent", null); + assertThatThrownBy(() -> CommandSource.replay(inherited, List.of(absentDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + assertThatThrownBy(() -> CommandSource.replay(List.of(), List.of(absentDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + var secondDelete = + new CommandSource.Mutation( + "1", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "look", null); + assertThatThrownBy( + () -> CommandSource.replay(inherited, List.of(operations.getFirst(), secondDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + assertThatThrownBy( + () -> CommandSource.replay(inherited, List.of(operations.get(1), operations.get(0)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void mixedControlPlaneCommitReturnsCommandEvidenceWithoutTakingOwnerOutcomeOwnership() { + UUID commitId = UUID.randomUUID(); + var commandRevision = + revision("0", UUID.randomUUID(), CommandSource.upsertPayload(command("look", "l"))); + var policyRevision = + revision( + "1", + UUID.randomUUID(), + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"main\",\"policy\":{}}"); + var policyScope = + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + TARGET.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"); + var binding = + binding( + commitId, + List.of(commandRevision, policyRevision), + List.of(commandScope("0"), policyScope)); + + var mutations = CommandSource.mutations(binding); + assertThat(mutations).hasSize(1); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isTrue(); + var snapshot = + new CommandSnapshot( + binding, + "1", + null, + "sha256:" + "b".repeat(64), + CommandSource.replay(List.of(), mutations)); + var evidence = new CommandApplication(binding, null, "0", mutations, snapshot); + assertThat(evidence.commandAppliedEpoch()) + .isEqualTo( + new DraftCommitCoordinatorRepository.AppliedEpoch( + CommandSource.SCOPE, + TARGET.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + "0", + "1")); + byte[] applicationBytes = evidence.canonicalBytes(); + byte[] schemaBytes = CommandSource.APPLICATION_SCHEMA.getBytes(StandardCharsets.UTF_8); + assertThat(applicationBytes).isNotEmpty(); + assertThat(ByteBuffer.wrap(applicationBytes).getInt()).isEqualTo(schemaBytes.length); + assertThat(ByteBuffer.wrap(applicationBytes).getInt(4 + schemaBytes.length)).isZero(); + } + + @Test + void rejectsAmbiguousAliasesAndKeepsTheEntireEffectiveSet() { + var first = definition("look", "inspect", UUID.randomUUID(), UUID.randomUUID(), "0"); + var collision = definition("inspect", "peek", UUID.randomUUID(), UUID.randomUUID(), "1"); + assertThatThrownBy(() -> CommandSource.replay(List.of(first, collision), List.of())) + .isInstanceOf(IllegalArgumentException.class); + + List inherited = new ArrayList<>(); + for (int index = 0; index < 140; index++) { + inherited.add( + definition( + "command-" + index, "alias-" + index, UUID.randomUUID(), UUID.randomUUID(), "0")); + } + assertThat(CommandSource.replay(inherited, List.of())).hasSize(140); + } + + @Test + void snapshotRoundTripAndCaptureBindTheActualSelectedCommit() throws Exception { + GameDesignPublicationOperation operation = IsolatedPublicationOperationFixtures.fresh(TARGET); + var selected = operation.account().input().selection().selectedCommit(); + var snapshot = new CommandSnapshot(selected, "0", null, "sha256:" + "a".repeat(64), List.of()); + String canonicalJson = snapshot.canonicalJson(); + assertThat(CommandSnapshot.fromStored(canonicalJson)).isEqualTo(snapshot); + assertThat(canonicalJson).contains("\"inheritedCommitId\":\"\""); + List invalidInheritedCommitIds = + List.of( + canonicalJson.replace(",\"inheritedCommitId\":\"\"", ""), + canonicalJson.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":null"), + canonicalJson.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":7"), + canonicalJson.replace( + "\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":\"not-a-uuid\"")); + for (String invalidJson : invalidInheritedCommitIds) { + assertThatThrownBy(() -> CommandSnapshot.fromStored(invalidJson)) + .isInstanceOf(IllegalArgumentException.class); + } + var capture = new CommandSnapshot.Capture(operation, snapshot); + assertThat(new String(capture.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains("game-design-command-source-capture/v1"); + + var wrongCommit = + DraftCommitBinding.create( + selected.target(), + UUID.randomUUID(), + UUID.randomUUID(), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + assertThatThrownBy( + () -> + new CommandSnapshot.Capture( + operation, + new CommandSnapshot( + wrongCommit, "0", null, "sha256:" + "a".repeat(64), List.of()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void freshGenesisReceiptRequiresExactVersionInsertTransactionIdentity() { + var receipt = new CommandSource.NewDraftGenesisReceipt(TARGET, UUID.randomUUID(), "1234567"); + assertThat(receipt.digest()).startsWith("sha256:"); + assertThat(new String(receipt.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains("1234567"); + assertThatThrownBy( + () -> new CommandSource.NewDraftGenesisReceipt(TARGET, UUID.randomUUID(), "0")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CommandSource.Definition definition( + String commandId, String alias, UUID commitId, UUID revisionId, String revisionOrder) { + return new CommandSource.Definition( + commandId, command(commandId, alias), commitId, revisionId, revisionOrder); + } + + private static String command(String id, String alias) { + return "{\"schemaVersion\":1,\"commandId\":\"" + + id + + "\",\"semanticOwner\":\"WORLD\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"" + + alias + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," + + "\"legacyExtension\":{\"kept\":true}}"; + } + + private static DraftCommitBinding.RevisionPayload revision( + String order, UUID id, String payload) { + return new DraftCommitBinding.RevisionPayload( + order, id, Owner.GAME_DESIGN_CONTROL_PLANE, payload); + } + + private static DraftCommitBinding.AffectedUnit commandScope(String epoch) { + return new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + TARGET.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + epoch); + } + + private static DraftCommitBinding binding( + UUID commitId, + List revisions, + List units) { + return DraftCommitBinding.create( + TARGET, UUID.randomUUID(), commitId, "ISOLATED-exact-base", revisions, units); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java new file mode 100644 index 0000000000..f01ca0b6f0 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.junit.jupiter.api.Test; + +class RealmPolicyApplicationTest { + @Test + void genesisApplicationFramesAbsentInheritedCommitAsEmptyBytesAndBindsOwnerOutcome() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 17L, + "tenant-key", + 23L, + "tenant-key", + "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis:" + UUID.randomUUID(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "world-revision")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM", + "room", + "0"))); + var genesis = new RealmPolicyGenesis(target, UUID.randomUUID(), "1"); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of()); + var application = new RealmPolicyApplication(genesis, null, "0", snapshot); + + ByteArrayOutputStream expected = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(expected, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(expected, "true"); + DraftAuthorizationFenceBinding.frame(expected, genesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(expected, "false"); + DraftAuthorizationFenceBinding.frame(expected, new byte[0]); + DraftAuthorizationFenceBinding.frame(expected, "0"); + DraftAuthorizationFenceBinding.frame(expected, snapshot.canonicalBytes()); + + var ownerOutcome = application.ownerOutcome(); + assertThat(application.canonicalBytes()).containsExactly(expected.toByteArray()); + assertThat(ownerOutcome) + .isEqualTo( + new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "realm-policy:" + binding.commitId(), + expected.toByteArray(), + List.of( + new AppliedEpoch( + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + "1")))); + + UUID inheritedCommitId = UUID.randomUUID(); + var inherited = new RealmPolicyApplication(inheritedCommitId, "0", snapshot); + ByteArrayOutputStream expectedInherited = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + expectedInherited, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(expectedInherited, "false"); + DraftAuthorizationFenceBinding.frame(expectedInherited, new byte[0]); + DraftAuthorizationFenceBinding.frame(expectedInherited, "true"); + DraftAuthorizationFenceBinding.frame(expectedInherited, inheritedCommitId.toString()); + DraftAuthorizationFenceBinding.frame(expectedInherited, "0"); + DraftAuthorizationFenceBinding.frame(expectedInherited, snapshot.canonicalBytes()); + + assertThat(inherited.canonicalBytes()).containsExactly(expectedInherited.toByteArray()); + assertThat(inherited.canonicalBytes()).isNotEqualTo(application.canonicalBytes()); + assertThat(inherited.ownerOutcome().resultBytes()) + .containsExactly(expectedInherited.toByteArray()); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java new file mode 100644 index 0000000000..61a8caa3d9 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java @@ -0,0 +1,429 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +/** + * Adapter tests use isolated owner evidence and context identities, not DB or physical mTLS proof. + */ +class RealmPolicyPublicationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void rejectsAbsentWrongNamespaceAndEndUserPeersBeforeDecodeOrOwnerAccess() { + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var malformed = ListPublishedRealmEntryPoliciesRequest.getDefaultInstance(); + + assertThat(callList(handler, malformed, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(callList(handler, malformed, peer("account-service", NAMESPACE)).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(callList(handler, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + try { + assertThat(callList(handler, malformed, peer("game-session-service", NAMESPACE)).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void malformedAndWrongRequestNamespacesAreDeniedBeforeOwnerAccess() { + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var peer = peer("game-session-service", NAMESPACE); + var malformed = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .build(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var unknownRequest = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId("99999999-9999-4999-8999-999999999999") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .setUnknownFields(unknown) + .build(); + var wrongNamespace = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("other") + .setReadRequestId("99999999-9999-4999-8999-999999999999") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .build(); + + assertThat(callList(handler, malformed, peer).error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callList(handler, unknownRequest, peer).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callList(handler, wrongNamespace, peer).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void readsAndReturnsTheCompleteSetAndDoesNotFallBackForAnAbsentSelector() throws Exception { + var fixture = publishedSet(); + var owner = mock(RealmPolicyPublicationService.class); + when(owner.readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId())) + .thenReturn(Optional.of(fixture.set())); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var peer = peer("game-session-service", NAMESPACE); + + var listRequest = listRequest(fixture); + var listedWire = + callList(handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest), peer); + assertThat(listedWire.error).isNull(); + var listed = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listedWire.response); + assertThat(listed.target()).isEqualTo(fixture.target()); + assertThat(listed.policyCount()).isEqualTo(1); + assertThat(listed.policies()).hasSize(1); + assertThat(listed.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(listed.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(listed.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(listed.terminalEvidenceBytes()).isEqualTo(fixture.set().terminalEvidenceBytes()); + + var resolveRequest = resolveRequest(fixture, "main"); + var resolvedWire = + callResolve( + handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest), peer); + assertThat(resolvedWire.error).isNull(); + var resolved = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolvedWire.response); + assertThat(resolved).isEqualTo(listed); + + var missingSelector = resolveRequest(fixture, "absent"); + var missing = + callResolve( + handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(missingSelector), peer); + assertThat(missing.error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.response).isNull(); + verify(owner, org.mockito.Mockito.times(3)) + .readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()); + } + + @Test + void absentOwnerEvidenceUnavailableStorageAndContradictoryEvidenceHaveDistinctStatuses() + throws Exception { + var fixture = publishedSet(); + var request = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest(fixture)); + var peer = peer("game-session-service", NAMESPACE); + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))).thenReturn(Optional.empty()); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.NOT_FOUND); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow(new org.jooq.exception.DataAccessException("ISOLATED storage unavailable")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow( + new org.springframework.transaction.CannotCreateTransactionException( + "ISOLATED transaction unavailable")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + var resolve = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest(fixture, "main")); + assertThat(callResolve(handler, resolve, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + verify(owner, org.mockito.Mockito.times(4)).readPublishedSet(any(UUID.class), any(UUID.class)); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow(new IllegalStateException("ISOLATED contradictory owner evidence")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest(Fixture fixture) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + NAMESPACE, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + } + + static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequest( + Fixture fixture, String realmSlug) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + NAMESPACE, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + "earth", + realmSlug); + } + + static Fixture publishedSet() throws Exception { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42L, + "tenant-key", + 7L, + "tenant-key", + "NEW_GAME_ROW"); + GameDesignPublicationOperation operation = IsolatedPublicationOperationFixtures.fresh(target); + var selection = operation.account().input().selection(); + var source = + new RealmPolicySource.Policy( + selection.selectedCommit().commitId(), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "main-policy-v1", + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON)); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release(operation), 6L); + byte[] capture = capture(operation, source, "43"); + String policyDigest = + RealmPolicyPublishedEvidence.policyDigest( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + source); + var policy = + new RealmPolicyPublishedEvidence.Policy( + UUID.fromString("44444444-4444-4444-8444-444444444444"), source, policyDigest); + var policies = List.of(policy); + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + terminal.releaseContent().versionNumber(), + selection.selectedCommit().commitId(), + "43", + terminal.releaseContent().publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + var ownerSet = + new RealmPolicyPublishedEvidence.PublishedSet( + target, + terminal.releaseContent().versionNumber(), + selection.selectedCommit().commitId(), + "43", + terminal.releaseContent().publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + 1, + setDigest, + policies); + return new Fixture(target, ownerSet); + } + + private static byte[] capture( + GameDesignPublicationOperation operation, RealmPolicySource.Policy source, String epoch) + throws IOException { + var policy = JSON.readTree(source.policy().canonicalJson()); + var snapshot = + Map.of( + "schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", operation.account().input().selection().selectedCommit().canonicalJson(), + "bindingDigest", operation.account().input().selection().selectedCommit().digest(), + "sourceEpoch", epoch, + "policies", + List.of( + Map.of( + "commitId", source.commitId().toString(), + "revisionId", source.revisionId().toString(), + "logicalRevisionId", source.logicalRevisionId(), + "policy", policy))); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } + + private static ReleaseContent release(GameDesignPublicationOperation operation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + List.of("LOOK"), + "generation-1", + operation.world()); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static ListCollector callList( + RealmPolicyPublicationGrpcService handler, + ListPublishedRealmEntryPoliciesRequest request, + GrpcPeerIdentity peer) { + var observer = new ListCollector(); + withPeer(peer, () -> handler.listPublishedRealmEntryPolicies(request, observer)); + return observer; + } + + private static ResolveCollector callResolve( + RealmPolicyPublicationGrpcService handler, + ResolvePublishedRealmEntryPolicyRequest request, + GrpcPeerIdentity peer) { + var observer = new ResolveCollector(); + withPeer(peer, () -> handler.resolvePublishedRealmEntryPolicy(request, observer)); + return observer; + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + record Fixture( + DraftCommitBinding.TargetProof target, RealmPolicyPublishedEvidence.PublishedSet set) {} + + private static final class ListCollector + implements StreamObserver { + private ListPublishedRealmEntryPoliciesResponse response; + private Status.Code error; + + @Override + public void onNext(ListPublishedRealmEntryPoliciesResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class ResolveCollector + implements StreamObserver { + private ResolvePublishedRealmEntryPolicyResponse response; + private Status.Code error; + + @Override + public void onNext(ResolvePublishedRealmEntryPolicyResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java new file mode 100644 index 0000000000..6ebe197e69 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java @@ -0,0 +1,345 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Loopback transport proof for the production handler/interceptor; owner data stays isolated. */ +class RealmPolicyPublicationMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SERVER_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + var pair = newRsaKeyPair(); + var name = new X500Name("CN=Realm Policy Test CA, O=FireMUD Test"); + var ca = issueCertificate(name, pair.getPublic(), name, pair.getPrivate(), true); + pki = + new TestPki( + ca, + issueLeaf(name, pair.getPrivate(), "game-design-server", SERVER_URI), + issueLeaf( + name, + pair.getPrivate(), + "game-session-client", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-service-client", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-namespace-client", + "spiffe://firemud/ns/other/sa/game-session-service")); + } + + @Test + void trustedWrongServiceAndNamespaceDenyBeforeMalformedDecodeOrOwnerRead() throws Exception { + var owner = mock(RealmPolicyPublicationService.class); + var server = server(owner); + try { + for (var identity : List.of(pki.wrongService(), pki.wrongNamespace())) { + var channel = channel(server, identity); + try { + assertThat( + listFailure(channel, ListPublishedRealmEntryPoliciesRequest.getDefaultInstance())) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + close(channel); + } + } + verifyNoInteractions(owner); + } finally { + stopServer(server); + } + } + + @Test + void exactGameSessionPeerReadsTheFullSetAndResolvesOnlyItsExactSelector() throws Exception { + var fixture = RealmPolicyPublicationGrpcServiceTest.publishedSet(); + var owner = mock(RealmPolicyPublicationService.class); + when(owner.readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId())) + .thenReturn(Optional.of(fixture.set())); + var server = server(owner); + try { + var channel = channel(server, pki.gameSession()); + try { + var listRequest = RealmPolicyPublicationGrpcServiceTest.listRequest(fixture); + var listed = + stub(channel) + .listPublishedRealmEntryPolicies( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest)); + var complete = PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listed); + assertThat(complete.policyCount()).isEqualTo(fixture.set().policyCount()); + assertThat(complete.policies()).hasSize(fixture.set().policyCount()); + assertThat(complete.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(complete.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(complete.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(complete.terminalEvidenceBytes()) + .isEqualTo(fixture.set().terminalEvidenceBytes()); + + var resolveRequest = RealmPolicyPublicationGrpcServiceTest.resolveRequest(fixture, "main"); + var resolved = + stub(channel) + .resolvePublishedRealmEntryPolicy( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest)); + var selected = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolved); + assertThat(selected).isEqualTo(complete); + assertThat(selected.policies()) + .anySatisfy( + policy -> { + assertThat(policy.policy().worldSlug()).isEqualTo("earth"); + assertThat(policy.policy().realmSlug()).isEqualTo("main"); + }); + verify(owner, times(2)) + .readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()); + } finally { + close(channel); + } + } finally { + stopServer(server); + } + } + + @Test + void exactPeerRejectsMalformedAndMismatchedNamespaceBeforeOwnerRead() throws Exception { + var owner = mock(RealmPolicyPublicationService.class); + var server = server(owner); + try { + var channel = channel(server, pki.gameSession()); + try { + assertThat( + listFailure(channel, ListPublishedRealmEntryPoliciesRequest.getDefaultInstance())) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var fixture = RealmPolicyPublicationGrpcServiceTest.publishedSet(); + var mismatchedNamespace = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + RealmPolicyPublicationGrpcServiceTest.listRequest(fixture)) + .toBuilder() + .setTargetNamespace("other") + .build(); + assertThat(listFailure(channel, mismatchedNamespace)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + close(channel); + } + verifyNoInteractions(owner); + } finally { + stopServer(server); + } + } + + private static Server server(RealmPolicyPublicationService owner) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.server().privateKey(), pki.server().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new RealmPolicyPublicationGrpcService(owner, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), + Set.of( + PublishedRealmEntryPolicyServiceGrpc + .getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc + .getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName())))) + .build() + .start(); + } + + private static ManagedChannel channel(Server server, TestCertificate identity) throws Exception { + return NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate()) + .build()) + .build(); + } + + private static PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + stub(ManagedChannel channel) { + return PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(SERVER_URI)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(SERVER_URI)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } + + private static Status.Code listFailure( + ManagedChannel channel, ListPublishedRealmEntryPoliciesRequest request) { + try { + stub(channel).listPublishedRealmEntryPolicies(request); + return null; + } catch (StatusRuntimeException failure) { + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isFalse(); + return Status.fromThrowable(failure).getCode(); + } + } + + private static void close(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca) + throws Exception { + return issueCertificate(subject, publicKey, issuer, issuerPrivateKey, ca, null); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate server, + TestCertificate gameSession, + TestCertificate wrongService, + TestCertificate wrongNamespace) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java new file mode 100644 index 0000000000..86910a1677 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java @@ -0,0 +1,333 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class RealmPolicyPublishedEvidenceTest { + @Test + void policyDigestMatchesIndependentCanonicalKnownVector() { + var target = + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42, + "tenant-42", + 7, + "tenant-42", + "NEW_GAME_ROW"); + var source = + new RealmPolicySource.Policy( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "main-policy-v1", + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper())); + UUID policyId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + source); + + assertThat(digest) + .isEqualTo("sha256:1cb51d94ec2825d1d598fa30c197e6ce52d23b8a62106b04babcaafc92be2f47"); + var changedPolicy = + new RealmPolicySource.Policy( + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Changed\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper())); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + changedPolicy)) + .isNotEqualTo(digest); + } + + @Test + void targetProofUsesCompleteStableIdentityAndExactDecimalRowIds() { + var target = target(); + String encoded = RealmPolicyPublishedEvidence.targetProofJson(target); + var decoded = new ObjectMapper().readTree(encoded); + + assertThat(decoded.size()).isEqualTo(7); + assertThat(decoded.path("canonicalTenantId").asText()) + .isEqualTo(target.canonicalTenantId().toString()); + assertThat(decoded.path("canonicalVersionId").asText()) + .isEqualTo(target.canonicalVersionId().toString()); + assertThat(decoded.path("gameDesignVersionRowId").asText()) + .isEqualTo(Long.toString(target.gameDesignVersionRowId())); + assertThat(decoded.path("sourceGameRowId").asText()) + .isEqualTo(Long.toString(target.sourceGameRowId())); + assertThat(RealmPolicyPublishedEvidence.targetProofJson(target)) + .isEqualTo(RealmPolicyPublishedEvidence.targetProofJson(target)); + } + + @Test + void policyAndCompleteSetDigestsBindOriginalSourceAndActualReleaseEvidence() { + var target = target(); + var main = source("main", true, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + var privateRealm = + source("private", false, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + UUID policyId = UUID.randomUUID(); + String bundleRef = "actual-owner-bundle-reference"; + String bundleDigest = digest('a'); + String workflow = "publish-workflow-original"; + String manifest = digest('b'); + + String originalPolicyDigest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, main); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, main)) + .isEqualTo(originalPolicyDigest); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, "different-bundle", bundleDigest, workflow, manifest, main)) + .isNotEqualTo(originalPolicyDigest); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, digest('c'), workflow, manifest, main)) + .isNotEqualTo(originalPolicyDigest); + var changedRevision = + source("main", true, main.commitId(), UUID.randomUUID(), UUID.randomUUID()); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, changedRevision)) + .isNotEqualTo(originalPolicyDigest); + + // Use stable row identities so the set comparison covers only the requested byte change. + var secondId = UUID.randomUUID(); + var rows = + List.of( + new RealmPolicyPublishedEvidence.Policy(policyId, main, originalPolicyDigest), + new RealmPolicyPublishedEvidence.Policy( + secondId, + privateRealm, + RealmPolicyPublishedEvidence.policyDigest( + secondId, + target, + 12, + bundleRef, + bundleDigest, + workflow, + manifest, + privateRealm))); + String originalSet = + setDigest(target, main, bundleRef, bundleDigest, workflow, manifest, rows, new byte[] {1}); + assertThat( + setDigest( + target, + main, + bundleRef, + bundleDigest, + workflow, + manifest, + List.of(rows.get(1), rows.get(0)), + new byte[] {1})) + .isEqualTo(originalSet); + assertThat( + setDigest( + target, main, bundleRef, bundleDigest, workflow, manifest, rows, new byte[] {2})) + .isNotEqualTo(originalSet); + assertThat( + setDigest( + target, main, bundleRef, digest('c'), workflow, manifest, rows, new byte[] {1})) + .isNotEqualTo(originalSet); + } + + @Test + void publishedSetUsesContentValueSemanticsForStoredEvidenceBytes() throws Exception { + var original = RealmPolicyPublicationGrpcServiceTest.publishedSet().set(); + var copied = + new RealmPolicyPublishedEvidence.PublishedSet( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + original.publishedReleaseBundleRef(), + original.publishedReleaseBundleDigest(), + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + original.operationBytes(), + original.captureBytes(), + original.terminalEvidenceBytes(), + original.policyCount(), + original.policySetDigest(), + original.policies()); + + assertThat(copied).isEqualTo(original); + assertThat(copied.hashCode()).isEqualTo(original.hashCode()); + assertThat(copied.toString()).isEqualTo(original.toString()); + + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + var release = terminal.releaseContent(); + String changedBundleRef = original.publishedReleaseBundleRef() + "-changed"; + var changedRelease = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + changedBundleRef, + release.versionNumber(), + release.attestationSchemaVersion(), + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + release.participantDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + byte[] changedTerminal = + new GameDesignPublicationTerminalEvidence( + original.operationBytes(), + terminal.outcome(), + changedRelease, + original.publicationVersionStateEpoch()) + .canonicalBytes(); + var originalPolicy = original.policies().get(0); + String changedBundleDigest = changedRelease.contentDigest(); + String changedPolicyDigest = + RealmPolicyPublishedEvidence.policyDigest( + originalPolicy.policyId(), + original.target(), + original.versionNumber(), + changedBundleRef, + changedBundleDigest, + original.publishWorkflowId(), + original.manifestHash(), + originalPolicy.source()); + var changedPolicies = + List.of( + new RealmPolicyPublishedEvidence.Policy( + originalPolicy.policyId(), originalPolicy.source(), changedPolicyDigest)); + String changedDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + changedBundleRef, + changedBundleDigest, + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + original.operationBytes(), + original.captureBytes(), + changedTerminal, + changedPolicies); + var changed = + new RealmPolicyPublishedEvidence.PublishedSet( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + changedBundleRef, + changedBundleDigest, + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + original.operationBytes(), + original.captureBytes(), + changedTerminal, + original.policyCount(), + changedDigest, + changedPolicies); + + assertThat(changed).isNotEqualTo(original); + assertThat(changed.toString()).isNotEqualTo(original.toString()); + } + + private String setDigest( + TargetProof target, + RealmPolicySource.Policy main, + String bundleRef, + String bundleDigest, + String workflow, + String manifest, + List rows, + byte[] terminal) { + return RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + 12, + main.commitId(), + "43", + bundleRef, + bundleDigest, + workflow, + manifest, + 19, + new byte[] {3}, + new byte[] {4}, + terminal, + rows); + } + + private static RealmPolicySource.Policy source( + String realm, + boolean production, + UUID commitId, + UUID revisionId, + UUID logicalRevisionSuffix) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + return new RealmPolicySource.Policy( + commitId, revisionId, "source-" + logicalRevisionSuffix, policy); + } + + private static TargetProof target() { + return new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + Long.MAX_VALUE - 3, + "ISOLATED-tenant", + Long.MAX_VALUE - 7, + "ISOLATED-tenant", + "NEW_GAME_ROW"); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java new file mode 100644 index 0000000000..3a0b00d480 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.gamedesign.publication; + +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 java.util.stream.IntStream; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class RealmPolicySourceTest { + @Test + void draftPolicyStateCanBeEmptyOrIncompleteWithoutPublicationCardinality() { + var empty = new RealmPolicySnapshot(binding(), "0", List.of()); + assertThat(RealmPolicySnapshot.fromStored(empty.canonicalJson()).policies()).isEmpty(); + var hidden = policy("private", false); + assertThat(RealmPolicySource.effective(List.of(), List.of(hidden))).containsExactly(hidden); + assertThatThrownBy(() -> RealmPolicySource.ordered(empty.policies())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(hidden))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactCanonicalSnapshotRetainsOriginalAuthoredProvenanceAndDisjointInheritance() { + var original = policy("main", true); + var binding = binding(); + var snapshot = + new RealmPolicySnapshot(binding, "90071992547409931234567890", List.of(original)); + assertThat(RealmPolicySnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(RealmPolicySource.effective(snapshot.policies(), List.of())) + .containsExactly(original); + assertThatThrownBy(() -> RealmPolicySnapshot.fromStored(snapshot.canonicalJson() + " ")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void closedTypedRevisionRejectsMalformedUnknownAndUnsupportedFields() { + var binding = binding(); + var original = policy("main", true); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-main\",\"policy\":" + + original.policy().canonicalJson() + + "}"; + var input = + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload); + assertThat(RealmPolicySource.revision(binding, input).logicalRevisionId()) + .isEqualTo("authored-main"); + for (String malformed : + List.of( + payload.replace("PRESEEDED_ONLY", "AUTO_PROVISIONED"), + payload.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"extra\":true"), + payload.replace( + "\"revisionKind\":", + "\"revisionKind\":\"REALM_ENTRY_POLICY\",\"revisionKind\":"))) { + assertThatThrownBy( + () -> + RealmPolicySource.revision( + binding, + new DraftCommitBinding.RevisionPayload( + "0", input.revisionId(), input.owner(), malformed))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void closedTypedRevisionAcceptsExactDeleteEnvelopeAndPreservesUpsertPolicyApi() { + var target = binding().target(); + var upsert = + policyRevision( + "0", + UUID.randomUUID(), + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-main\",\"policy\":" + + policy("main", true).policy().canonicalJson() + + "}"); + var upsertBinding = mutationBinding(target, List.of(upsert)); + assertThat(RealmPolicySource.mutation(upsertBinding, upsert)) + .isEqualTo(RealmPolicySource.revision(upsertBinding, upsert)); + + UUID deleteRevisionId = UUID.randomUUID(); + var deletion = + policyRevision( + "0", + deleteRevisionId, + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-delete-main\"," + + "\"operation\":\"DELETE\",\"worldSlug\":\"world\",\"realmSlug\":\"main\"}"); + var deleteBinding = mutationBinding(target, List.of(deletion)); + assertThat(RealmPolicySource.mutation(deleteBinding, deletion)) + .isEqualTo( + new RealmPolicySource.Deletion( + deleteBinding.commitId(), + deleteRevisionId, + "authored-delete-main", + "world", + "main")); + + for (String malformed : + List.of( + deletion.payload().replace("\"operation\":\"DELETE\"", "\"operation\":\"UPSERT\""), + deletion + .payload() + .replace("\"realmSlug\":\"main\"}", "\"realmSlug\":\"main\",\"extra\":true}"), + deletion.payload().replace("\"worldSlug\":\"world\"", "\"worldSlug\":\"World\""))) { + var malformedInput = policyRevision("0", deleteRevisionId, malformed); + assertThatThrownBy(() -> RealmPolicySource.mutation(deleteBinding, malformedInput)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void explicitDeletionAppliesBeforeFinalTenantRealmUniquenessCheck() { + var retained = policy("old-world", "main", true); + var unrelated = policy("old-world", "side", false); + var deletion = + new RealmPolicySource.Deletion( + UUID.randomUUID(), UUID.randomUUID(), "authored-main", "old-world", "main"); + var moved = policy("new-world", "main", true); + + assertThat(RealmPolicySource.effective(List.of(retained, unrelated), List.of(deletion, moved))) + .containsExactly(moved, unrelated); + assertThatThrownBy( + () -> + RealmPolicySource.effective( + List.of(retained), + List.of( + new RealmPolicySource.Deletion( + UUID.randomUUID(), + UUID.randomUUID(), + "authored-delete-missing", + "old-world", + "missing")))) + .hasMessageContaining("absent policy selector"); + assertThatThrownBy( + () -> + RealmPolicySource.effective( + List.of(retained), + List.of( + new RealmPolicySource.Deletion( + UUID.randomUUID(), + UUID.randomUUID(), + "different-logical-identity", + "old-world", + "main")))) + .hasMessageContaining("logical revision identity does not match"); + assertThatThrownBy(() -> RealmPolicySource.effective(List.of(retained), List.of(moved))) + .hasMessageContaining("Duplicate tenant realm selector"); + } + + @Test + void effectiveSetRejectsDuplicateRealmAndProductionAndOverLimitInsteadOfTruncating() { + var main = policy("main", true); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(main, policy("main", false)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(main, policy("another", true)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(policy("hidden", false)))) + .isInstanceOf(IllegalArgumentException.class); + var bound = IntStream.range(0, 128).mapToObj(i -> policy("realm-" + i, i == 0)).toList(); + assertThat(RealmPolicySource.ordered(bound)).hasSize(128); + var oversized = new java.util.ArrayList<>(bound); + oversized.add(policy("last", false)); + assertThatThrownBy(() -> RealmPolicySource.ordered(oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RealmPolicySource.Policy policy(String realm, boolean production) { + return policy("world", realm, production); + } + + private static RealmPolicySource.Policy policy(String world, String realm, boolean production) { + String json = + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return new RealmPolicySource.Policy( + UUID.randomUUID(), + UUID.randomUUID(), + "authored-" + realm, + RealmEntryPolicy.parse(json, new ObjectMapper())); + } + + private static DraftCommitBinding.RevisionPayload policyRevision( + String order, UUID revisionId, String payload) { + return new DraftCommitBinding.RevisionPayload( + order, revisionId, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload); + } + + private static DraftCommitBinding mutationBinding( + DraftCommitBinding.TargetProof target, List revisions) { + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-base", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "owner", 1, "owner", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ISOLATED-world")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, "ROOM", "room", "ROOM", "room", "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java index e3769a7953..305a88352d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -3,14 +3,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleRepositoryTest { private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -18,6 +22,57 @@ class PublishedReleaseBundleRepositoryTest { private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @Test + void selectorEvidenceRequiresExactSourceAndReadbackPreservesOriginalBytes() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + var evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + TENANT_UUID, VERSION_UUID, 17L, "tenant-key", 7L, "tenant-key", "NEW_GAME_ROW")); + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + requested.setAttestationSchemaVersion("v2"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mandatory"); + requested.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + requested.setPublishWorkflowId("other-workflow"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source/workflow"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + requested.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString(PublishedWorldSelectorFixtures.participants(17L, evidence))); + var saved = fixture.repository().save(requested); + assertThat(saved.getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(requested.getWorldPublishedStartLocationEvidenceJson()); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId("tenant-key", 17L) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + assertThat(fixture.repository().save(requested)).usingRecursiveComparison().isEqualTo(saved); + requested.setParticipantDigestsJson("[]"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + @Test void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { try (Fixture fixture = fixture()) { @@ -155,8 +210,8 @@ private static Fixture fixture() throws Exception { + "generation_config_revision VARCHAR(128), " + "required_manifest_asset_keys_json CLOB NOT NULL, " + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " - + "world_published_start_location_evidence_json TEXT, " + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "world_published_start_location_evidence_json CLOB, " + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + "published_at TIMESTAMP NOT NULL)"); return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index bb5a58ce07..94bce5de72 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import org.junit.jupiter.api.Test; @@ -51,6 +52,13 @@ class TenantIdentityGrpcAuthWiringTest { private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final List CONFIGURED_PUBLIC_METHODS = + List.of( + FRESH_CREATION_METHOD, + PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName()); private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; @@ -65,7 +73,7 @@ class TenantIdentityGrpcAuthWiringTest { void defaultAndProductionProfilesAllowOnlyFreshReadAndRequireClientTls() throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); - assertThat(config.publicMethods()).containsExactly(FRESH_CREATION_METHOD); + assertThat(config.publicMethods()).containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -180,7 +188,7 @@ private static void withConfiguredInterceptor(Consumer act context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(FRESH_CREATION_METHOD); + .containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } 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 0b7181f3f0..19771f2919 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 @@ -14,6 +14,7 @@ import java.util.concurrent.atomic.AtomicReference; 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; @@ -94,6 +95,8 @@ class GameDesignGrpcServiceTest { private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); @@ -325,11 +328,55 @@ void publishVersionRequiresPublishRequestId() { } @Test - void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + void publishVersionRejectsPartialSelectedSourceIdentity() { + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion( + PublishVersionRequest.newBuilder() + .setTenantId(CANONICAL_TENANT_ID.toString()) + .setNotes("notes") + .setPublishRequestId("publish-request-1") + .setVersionId(CANONICAL_VERSION_ID.toString()) + .build(), + observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); + } + + @Test + void publishVersionMapsMissingOwnerAuthorizationToExplicitDenial() throws Exception { + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow( new IllegalStateException( - "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match")); + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: exact current authorization required")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); + } + + assertEquals("PUBLICATION_AUTHORIZATION_UNAVAILABLE", ref.get().getError().getCode()); + } + + @Test + void publishVersionLegacyShapeOnlyUsesRetainedTerminalReplay() throws Exception { + Mockito.when(versionService.replayLegacyFullVersion("tenant-1", "notes", "legacy-1")) + .thenReturn( + new VersionDto( + 10L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -337,11 +384,50 @@ void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { PublishVersionRequest.newBuilder() .setTenantId("tenant-1") .setNotes("notes") - .setPublishRequestId("publish-request-1") + .setPublishRequestId("legacy-1") + .build(), + observerFor(ref)); + } + + assertEquals(10L, ref.get().getVersionId()); + Mockito.verify(versionService).replayLegacyFullVersion("tenant-1", "notes", "legacy-1"); + Mockito.verify(versionService, Mockito.never()) + .publishVersion(Mockito.any(PublishIntent.class)); + } + + @Test + void publishVersionMapsFreshLegacyPublicationGuardToExplicitDenial() throws Exception { + Mockito.when(versionService.replayLegacyFullVersion("tenant-1", "notes", "fresh-1")) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion( + PublishVersionRequest.newBuilder() + .setTenantId("tenant-1") + .setNotes("notes") + .setPublishRequestId("fresh-1") .build(), observerFor(ref)); } + assertEquals("FULL_VERSION_PUBLICATION_UNAVAILABLE", ref.get().getError().getCode()); + Mockito.verify(versionService).replayLegacyFullVersion("tenant-1", "notes", "fresh-1"); + } + + @Test + void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) + .thenThrow( + new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); + } + assertEquals("PUBLISH_ATTEMPT_SCOPE_MISMATCH", ref.get().getError().getCode()); } @@ -357,18 +443,12 @@ void publishVersionMapsTemporalKnownGateFailureCode() throws Exception { "FAILED", PublishGateFailureCode.PARTICIPANT_SET_MISMATCH.name(), "participant set mismatch")); - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow(gateFailure); 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)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("PARTICIPANT_SET_MISMATCH", ref.get().getError().getCode()); @@ -376,20 +456,14 @@ void publishVersionMapsTemporalKnownGateFailureCode() throws Exception { @Test void publishVersionMapsKnownIllegalArgumentPublishAttemptCode() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow( new IllegalArgumentException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: publish workflow does not match request")); 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)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("PUBLISH_ATTEMPT_IDENTITY_CONFLICT", ref.get().getError().getCode()); @@ -515,18 +589,12 @@ void publishScriptPatchVersionMapsUnknownIllegalArgumentToInvalidArgument() thro @Test void publishVersionKeepsUnknownIllegalStateFailuresInternal() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("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)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("INTERNAL", ref.get().getError().getCode()); @@ -583,18 +651,12 @@ void publishScriptPatchVersionMapsReplayedFailureCodeAndMessage() throws Excepti @Test void publishVersionMapsPendingReconciliationToStableApplicationError() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("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)); + service.publishVersion(selectedPublishRequest("request-1"), observerFor(ref)); } assertEquals( @@ -610,7 +672,7 @@ void publishVersionMapsOwnerProofRefusalToStableApplicationError() throws Except new MutationOwnerProofUnavailableException( "FULL_VERSION_PUBLICATION_UNAVAILABLE", "fresh and pending full-version publication require a production Draft association"); - Mockito.when(versionService.publishVersion("tenant-1", "notes", "request-1")) + Mockito.when(versionService.replayLegacyFullVersion("tenant-1", "notes", "request-1")) .thenThrow(refusal); AtomicReference ref = new AtomicReference<>(); @@ -1472,6 +1534,31 @@ private void underLaunchPeer(String serviceName, String peerNamespace, Runnable Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } + private static PublishIntent selectedIntent(String requestId) { + return new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + requestId, + "1", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); + } + + private static PublishVersionRequest selectedPublishRequest(String requestId) { + return PublishVersionRequest.newBuilder() + .setTenantId(CANONICAL_TENANT_ID.toString()) + .setVersionId(CANONICAL_VERSION_ID.toString()) + .setExpectedVersionStateEpoch("1") + .setSelectedCommitRequestId("33333333-3333-4333-8333-333333333333") + .setSelectedCommitId("44444444-4444-4444-8444-444444444444") + .setSelectedCommitDigest("sha256:" + "a".repeat(64)) + .setNotes("notes") + .setPublishRequestId(requestId) + .build(); + } + 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/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 5c4808eddd..20de82ffc8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -1,17 +1,30 @@ package net.firedevops.firemud.gamedesign.service.impl; +import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; +import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import org.junit.jupiter.api.BeforeEach; @@ -25,27 +38,251 @@ class PublishedReleaseBundleServiceImplTest { private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); @Mock private PublishedReleaseBundleRepository repository; + @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; + @Test + void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + throws Exception { + var evidence = selectorEvidence(); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + // ISOLATED source-repository response; this test covers service assembly only. + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-release"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(saved)); + return saved; + }); + var first = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence); + assertEquals("v2", first.attestationSchemaVersion()); + assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); + org.mockito.Mockito.clearInvocations(versionRepository, repository); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.empty()); + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + WorldPublishedStartLocationEvidence.fromStored(evidence.canonicalBytes())); + assertEquals(first.id(), retry.id()); + assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(first.worldPublishedStartLocationEvidence().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(versionRepository); + org.mockito.Mockito.verify(repository) + .requireSelectedCommandDefinitions(any(), any(), any(), any()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "changed", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest()); + assertThatThrownBy( + () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, logoManifest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("REPAIR_ATTESTATION_MISMATCH"); + } + + @Test + void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + throws Exception { + var evidence = selectorEvidence(); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "wrong-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants.subList(0, 4), + evidence)) + .isInstanceOf(IllegalArgumentException.class); + var world = participants.getFirst(); + var changed = new java.util.ArrayList<>(participants); + changed.set( + 0, + new PublishParticipantDigestDto( + world.participantKey(), + world.scopeValue(), + null, + world.appliedCommitId(), + "e".repeat(64), + 3, + null, + null, + null)); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + changed, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + var evidence = selectorEvidence(); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() + throws Exception { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v1"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + assertNull( + service.getPublishedReleaseBundle("tenant-1", 7L).worldPublishedStartLocationEvidence()); + var evidence = selectorEvidence(); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selector-ineligible"); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + retained.setAttestationSchemaVersion("v2"); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + } + + private VersionDto selectorVersion() { + return new VersionDto( + 7L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); - service = new PublishedReleaseBundleServiceImpl(repository, new ObjectMapper()); + service = + new PublishedReleaseBundleServiceImpl(repository, versionRepository, new ObjectMapper()); + Version source = new Version(); + source.setId(7L); + source.setTenantId("tenant-1"); + source.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + source.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(source)); } @Test - void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { - var refusal = - assertThrows( - IllegalStateException.class, + void legacyFullVersionCannotCreateV1BundleFromMutableRevisions() { + assertThatThrownBy( () -> service.createFullVersionBundle( - version(), "workflow-1", logoManifest(), "genrev-1", List.of())); - assertEquals( - "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation", - refusal.getMessage()); - org.mockito.Mockito.verifyNoInteractions(repository); + version(), "workflow-1", logoManifest(), "genrev-1", List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(repository, versionRepository); } @Test @@ -81,12 +318,17 @@ void corruptedSelectorEvidenceIsRejectedOnRead() { retained.setWorldPublishedStartLocationEvidenceJson("{}"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); - IllegalArgumentException denied = - assertThrows( - IllegalArgumentException.class, - () -> service.getPublishedReleaseBundle("tenant-1", 7L)); - assertEquals( - "published World selector evidence has missing or unsupported fields", denied.getMessage()); + assertThrows( + IllegalArgumentException.class, () -> service.getPublishedReleaseBundle("tenant-1", 7L)); + } + + private Version sourceIdentity() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + return version; } @Test @@ -160,17 +402,29 @@ void optionalReadDistinguishesMissingBundleWhileRequiredReadStillFails() { } @Test - void legacyFullVersionBundleRefusesEmptyManifestBeforeRepositoryAccess() { - var refusal = - assertThrows( - IllegalStateException.class, + void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Exception { + var evidence = selectorEvidence(); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) + .thenReturn(Optional.of(sourceIdentity())); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + + assertThatThrownBy( () -> service.createFullVersionBundle( - version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); - assertEquals( - "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation", - refusal.getMessage()); - org.mockito.Mockito.verifyNoInteractions(repository); + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); } private VersionDto version() { @@ -188,6 +442,100 @@ private VersionDto version() { LocalDateTime.now()); } + @Test + void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { + var evidence = selectorEvidence(); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-issued-reference-11"); + return saved; + }); + + var dto = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + logoManifest(), + "genrev-1", + participants, + evidence); + + assertEquals(11L, dto.id()); + assertEquals("tenant-1", dto.tenantId()); + assertEquals(7L, dto.versionId()); + assertEquals(8, dto.versionNumber()); + assertEquals(MANIFEST_HASH, dto.manifestHash()); + assertEquals(1, dto.manifestSchemaVersion()); + assertEquals(List.of(logoProof()), dto.artifactDigests()); + assertEquals("genrev-1", dto.generationConfigRevision()); + assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); + assertEquals(participants, dto.participantDigests()); + assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); + assertEquals("v2", dto.attestationSchemaVersion()); + assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); + assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); + assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); + assertThat(dto.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + } + + @Test + void selectedFullVersionBundleRejectsDuplicateCommandDefinitionAlias() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "hail"), commandDefinition("greet", "HAIL")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsDuplicateCanonicalCommandIds() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "hail"), commandDefinition("SALUTE", "greet")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsCanonicalIdAndAliasCollisions() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "greet"), commandDefinition("hail", "SALUTE")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsMalformedCommandEffectDeclaration() throws Exception { + assertSelectedCommandsRejected( + List.of(validCommandDefinition().replace("\"value\":1", "\"value\":\"one\"")), + IllegalArgumentException.class); + } + + private void assertSelectedCommandsRejected( + List commandDefinitions, Class exceptionType) + throws Exception { + var evidence = selectorEvidence(); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(commandDefinitions); + + assertThrows( + exceptionType, + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence)); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + private static ExportedAssetManifest emptyManifest() { return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); } 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 af51a6a237..6739464bd4 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 @@ -1,16 +1,54 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.time.OffsetDateTime; +import java.util.List; +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.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.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.VersionDto; +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.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; class TemporalVersionPublishActivitiesImplTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + @Test void pendingReconciliationIsReturnedAsNonterminalSnapshot() { VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); @@ -34,22 +72,148 @@ void pendingReconciliationIsReturnedAsNonterminalSnapshot() { } @Test - void unavailableFreshOrPendingPublicationPropagatesWithoutTerminalMutation() { - VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + void registeredActivityDeniesFreshAndPendingSelectedAndLegacyRequestsBeforeMutation() { + assertActivityDeniesBeforeMutation(false, false); + assertActivityDeniesBeforeMutation(false, true); + assertActivityDeniesBeforeMutation(true, false); + assertActivityDeniesBeforeMutation(true, true); + } + + private void assertActivityDeniesBeforeMutation(boolean selected, boolean pending) { + VersionRepository versions = mock(VersionRepository.class); + GameRepository games = mock(GameRepository.class); + PublishAttemptRepository attempts = mock(PublishAttemptRepository.class); + AssetExportService assetExports = mock(AssetExportService.class); + PublishAttemptService attemptService = mock(PublishAttemptService.class); + PublishGateService gates = mock(PublishGateService.class); + ControlPlaneDigestService controlPlane = mock(ControlPlaneDigestService.class); + VersionAssetArtifactService artifacts = mock(VersionAssetArtifactService.class); + PublishedReleaseBundleService bundles = mock(PublishedReleaseBundleService.class); + RecordedParticipantDigestService recordedDigests = mock(RecordedParticipantDigestService.class); + AuthoredDraftPublishSelectionRepository selections = + mock(AuthoredDraftPublishSelectionRepository.class); + VersionPublishCommandServiceImpl commandService = + new VersionPublishCommandServiceImpl( + versions, + games, + attempts, + Mappers.getMapper(VersionMapper.class), + assetExports, + attemptService, + gates, + controlPlane, + artifacts, + bundles, + recordedDigests, + selections); + + SelectionSnapshot reservation = selected ? selectedReservation() : null; + PublishIntent intent = selected ? reservation.selection().intent() : null; + String publishRequestId = selected ? intent.publishRequestId() : "request-1"; + String workflowId = + TemporalVersionPublishOrchestrator.workflowId( + selected ? intent.canonicalTenantId().toString() : "tenant-1", publishRequestId); PublishWorkflowRequest request = - new PublishWorkflowRequest( - "tenant-1", "notes", "request-1", "publish:tenant-1:publish-request:request-1"); - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException denial = - new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException(); - when(commandService.reconcileFullVersionPublish(request)).thenThrow(denial); - - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException propagated = - assertThrows( - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, - () -> new TemporalVersionPublishActivitiesImpl(commandService).reconcile(request)); - - assertSame(denial, propagated); - verify(commandService).reconcileFullVersionPublish(request); - verifyNoMoreInteractions(commandService); + new PublishWorkflowRequest("tenant-1", "notes", publishRequestId, workflowId, intent); + if (selected) { + when(selections.readByPublishRequest(intent.canonicalTenantId(), publishRequestId)) + .thenReturn(Optional.of(reservation)); + } + PublishAttempt attempt = null; + if (pending) { + attempt = new PublishAttempt(); + attempt.setTenantId("tenant-1"); + attempt.setVersionId(10L); + attempt.setVersionNumber(1); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setPublishWorkflowId(workflowId); + attempt.setStatus(PublishAttemptStatus.PENDING); + attempt.setRequestDigest(selected ? reservation.selection().digest() : null); + when(attempts.findByPublishWorkflowId(workflowId)).thenReturn(Optional.of(attempt)); + } else { + when(attempts.findByPublishWorkflowId(workflowId)).thenReturn(Optional.empty()); + } + + assertThrows( + IllegalStateException.class, + () -> new TemporalVersionPublishActivitiesImpl(commandService).reconcile(request)); + + verify(attempts, never()).save(any(PublishAttempt.class)); + verify(attempts, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(attemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(attemptService, never()).executeFullVersionTransaction(any()); + verify(versions, never()).save(any(Version.class)); + verify(assetExports, never()).exportAssets(any(String.class), any(Integer.class)); + verify(selections, never()).reserve(any(PublishIntent.class)); + verifyNoInteractions( + versions, + games, + assetExports, + attemptService, + gates, + controlPlane, + artifacts, + bundles, + recordedDigests); + if (pending) assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + } + + private SelectionSnapshot selectedReservation() { + UUID requestId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID commitId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-1", + List.of( + new RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "1"))); + PublishIntent intent = + new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "request-1", + "1", + "notes", + requestId, + commitId, + binding.digest()); + VisibilityFence fence = + new VisibilityFence( + target, + requestId, + commitId, + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + // The retained source selection is not Account permission or an authenticated World freeze. + return new SelectionSnapshot(selection, OffsetDateTime.parse("2026-10-08T00:00:00Z")); } } 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 c5266b5c5e..3658997741 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 @@ -6,17 +6,34 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; +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.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +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; @@ -30,6 +47,7 @@ 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.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -70,6 +88,8 @@ class VersionPublishCommandServiceImplTest { @Mock private VersionAssetArtifactService versionAssetArtifactService; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private RecordedParticipantDigestService recordedParticipantDigestService; + @Mock private AuthoredDraftPublishSelectionRepository authoredSelections; + @Mock private WorldPublishedStartLocationEvidence capturedWorldPublicationEvidence; private VersionPublishCommandServiceImpl service; @@ -81,6 +101,8 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(publishAttemptRepository.requirePublicationPending(any(PublishAttempt.class))) + .thenReturn(capturedWorldPublicationEvidence); when(versionAssetArtifactService.stageExport( any(String.class), any(Long.class), any(Integer.class), any(String.class))) .thenAnswer( @@ -120,11 +142,12 @@ void setup() { controlPlaneDigestService, versionAssetArtifactService, publishedReleaseBundleService, - recordedParticipantDigestService); + recordedParticipantDigestService, + authoredSelections); } @Test - void freshFullVersionPublishIsDeniedBeforeAnyMutation() { + void freshLegacyFullVersionRequestIsDeniedByCanonicalPublicationGuard() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException freshDenial = @@ -145,492 +168,324 @@ void freshFullVersionPublishIsDeniedBeforeAnyMutation() { assertThrows( VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); - - verify(publishAttemptRepository, org.mockito.Mockito.times(2)) - .findByPublishWorkflowId(workflowId); - verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); - verify(versionRepository, never()).save(any(Version.class)); - verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); verify(publishAttemptService, never()) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(publishGateService, never()) .collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class)); - verify(versionAssetArtifactService, never()) - .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + } + + @Test + void selectedPublishRequestRequiresDurableOriginalSelection() { + PublishIntent intent = selectedIntent(); + String workflowId = + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()); + PublishWorkflowRequest request = + new PublishWorkflowRequest( + "tenant-1", intent.notes(), intent.publishRequestId(), workflowId, intent); + + when(authoredSelections.readByPublishRequest( + intent.canonicalTenantId(), intent.publishRequestId())) + .thenReturn(Optional.empty()); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); + + assertTrue(thrown.getMessage().startsWith("PUBLISH_SELECTION_REQUIRED")); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).save(any(Version.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { + void legacyPendingAttemptIsDeniedBeforeReadbackOrMutation() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + attempt.setRequestDigest(null); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId))); + .thenReturn(Optional.of(attempt)); assertThrows( VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, () -> service.reconcileFullVersionPublish( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).save(any(Version.class)); + } - verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); - verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + @Test + void freshSelectedRequestIsDeniedBeforeReservationOrPublicationMutation() { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.empty()); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.reconcileFullVersionPublish(request)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); verify(versionRepository, never()).save(any(Version.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void pendingSelectedRequestIsDeniedBeforePublicationMutation() { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = selectedAttempt(reservation, request, 1); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.reconcileFullVersionPublish(request)); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(versionRepository, never()).save(any(Version.class)); verify(publishGateService, never()) .collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class)); - verify(publishedReleaseBundleService, never()) - .findPublishedReleaseBundle(any(String.class), any(Long.class)); - verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void privateMechanicsReservesVersionUsingTenantScopedSequence() { - Game game = new Game(); - game.setId(1L); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + void legacyFreshRequestDoesNotExportOrDeleteCandidateAssets() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; - Version latest = new Version(); - latest.setId(9L); - latest.setTenantId("tenant-1"); - latest.setVersionNumber(7); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) - .thenReturn(Optional.of(latest)); - - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(8); - savedDraft.setNotes("notes"); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - Version savedPublished = new Version(); - savedPublished.setId(10L); - savedPublished.setTenantId("tenant-1"); - savedPublished.setVersionNumber(8); - savedPublished.setNotes("notes"); - savedPublished.setVersionState(VersionLifecycleState.PUBLISHED); - savedPublished.setVersionStateEpoch(2L); - savedPublished.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft, savedPublished); + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); - 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)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn( - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedPublished)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + } - ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); - when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); - List participantDigests = + @Test + void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.RETIRED); + List driftedParticipantDigests = 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); - when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) - .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); - when(versionAssetArtifactService.markExportedUnattested( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "EXPORTED_UNATTESTED", - 1L, - MANIFEST_HASH, - "workflow-1", - null, - null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); - when(publishedReleaseBundleService.createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class))) - .thenReturn( - publishedReleaseBundleDto( - 1L, - "tenant-1", - 10L, - 8, - "v1", - "publish:tenant-1:publish-request:workflow-1", - MANIFEST_HASH, - List.of("logo.png", "manifest.json"), - participantDigests, - "genrev-tenant-1-10", - false, - null, - LocalDateTime.now())); - when(versionAssetArtifactService.markPublished( - any(String.class), - any(Long.class), - any(Long.class), - any(String.class), - any(String.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "PUBLISHED", - 2L, - MANIFEST_HASH, - "workflow-1", - null, + "GAME_DESIGN_CONTROL_PLANE", + "wrong-version", + "wrong-scope", + "changed", + 99, null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); + null)); + PublishedReleaseBundleDto bundle = + publishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v1", + workflowId, + MANIFEST_HASH, + List.of("manifest.json"), + driftedParticipantDigests, + "generation-revision", + false, + null, + LocalDateTime.now()); + VersionAssetArtifactStateDto driftedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PURGED", + 8L, + "different-manifest-hash", + "different-workflow", + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(driftedArtifact)); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("SUCCEEDED", snapshot.status()); - assertEquals(10L, snapshot.versionId()); - assertEquals(8, snapshot.versionNumber()); - verify(publishAttemptService) - .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); - verify(assetExportService).exportAssets("tenant-1", 8); - verify(recordedParticipantDigestService) - .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - - InOrder publishOrder = - inOrder( - publishGateService, - recordedParticipantDigestService, - versionAssetArtifactService, - assetExportService, - publishAttemptService); - publishOrder - .verify(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); - publishOrder - .verify(recordedParticipantDigestService) + verify(publishedReleaseBundleService).findPublishedReleaseBundle("tenant-1", 10L); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(recordedParticipantDigestService, never()) + .recordVerifiedDigests( + any(String.class), any(PublishType.class), any(String.class), any(List.class)); + verify(recordedParticipantDigestService, never()) .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); - publishOrder - .verify(versionAssetArtifactService) - .stageExport("tenant-1", 10L, 8, "publish:tenant-1:publish-request:workflow-1"); - publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); - publishOrder - .verify(publishAttemptService) + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService, never()) .recordFullVersionParticipantDigests(any(String.class), any(List.class)); } - @Test - void privateMechanicsRecordsTypedPublishGateFailures() { - 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()); + @ParameterizedTest + @EnumSource( + value = VersionLifecycleState.class, + names = {"PUBLISHED", "ACTIVE", "RETIRED"}) + void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting( + VersionLifecycleState lifecycleState) throws Exception { + SelectedSucceededReplayFixture fixture = selectedSucceededReplayFixture(lifecycleState); - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish(fixture.request()); - 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)); - 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))); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")) - .when(recordedParticipantDigestService) - .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); - - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - - assertEquals("FAILED", snapshot.status()); - assertEquals( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); - verify(publishAttemptService) - .markFullVersionFailed( - any(String.class), - org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), - org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); + assertEquals("SUCCEEDED", snapshot.status()); + verify(publishAttemptRepository).requirePublishedOperation(fixture.attempt()); + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + assertNoPublicationWrites(); } @Test - void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { - 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); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - 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)); - 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)); + void selectedSucceededReplayRejectsMismatchedCommittedBundle() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.ACTIVE); + String changedWorkflowId = fixture.request().publishWorkflowId() + ":changed"; + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(withWorkflowId(fixture.bundle(), changedWorkflowId))); - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); - assertEquals("FAILED", snapshot.status()); - assertEquals( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); - verify(publishAttemptService, never()) - .recordFullVersionParticipantDigests(any(String.class), any(List.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + assertNoPublicationWrites(); } @Test - void privateMechanicsDeletesExportedAssetsWhenAttestationWriteFails() { - 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()); + void selectedSucceededReplayRejectsMismatchedCommittedArtifact() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.RETIRED); + VersionAssetArtifactStateDto artifact = fixture.artifact(); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.of( + new VersionAssetArtifactStateDto( + artifact.tenantId(), + artifact.versionId(), + artifact.exportedVersionNumber(), + "PURGED", + artifact.stateEpoch(), + artifact.manifestHash(), + artifact.lastWorkflowId(), + artifact.lastErrorCode(), + artifact.lastErrorMessage(), + artifact.updatedAt(), + artifact.exportedManifestAssetKeys()))); - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); - 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)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(savedDraft)); - when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(exportedManifest(List.of("manifest.json"))); - 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))); - when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) - .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); - when(versionAssetArtifactService.markExportedUnattested( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "EXPORTED_UNATTESTED", - 1L, - MANIFEST_HASH, - "workflow-1", - null, - null, - LocalDateTime.now(), - List.of("manifest.json"))); - org.mockito.Mockito.doThrow(new IllegalStateException("bundle failed")) - .when(publishedReleaseBundleService) - .createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class)); + assertNoPublicationWrites(); + } - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + @Test + void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.ACTIVE); + org.mockito.Mockito.doThrow( + new IllegalStateException("ISOLATED retained publication gate mismatch")) + .when(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); - assertEquals("FAILED", snapshot.status()); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); + assertNoPublicationWrites(); } @Test - void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.RETIRED); - List driftedParticipantDigests = - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - "wrong-version", - "wrong-scope", - "changed", - 99, - null, - null)); - PublishedReleaseBundleDto bundle = - publishedReleaseBundleDto( - 1L, - "tenant-1", - 10L, - 1, - "v1", - workflowId, - MANIFEST_HASH, - List.of("manifest.json"), - driftedParticipantDigests, - "generation-revision", - false, - null, - LocalDateTime.now()); - VersionAssetArtifactStateDto driftedArtifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "PURGED", - 8L, - "different-manifest-hash", - "different-workflow", - null, - null, - LocalDateTime.now(), - List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) - .thenReturn(Optional.of(bundle)); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.of(driftedArtifact)); + void selectedSucceededReplayRejectsRecordedDigestMismatch() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.RETIRED); + org.mockito.Mockito.doThrow( + new IllegalStateException("ISOLATED retained participant digest mismatch")) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); - assertEquals("SUCCEEDED", snapshot.status()); - verify(publishedReleaseBundleService).findPublishedReleaseBundle("tenant-1", 10L); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); - verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); - verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); - verify(publishGateService, never()) - .collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class)); - verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(recordedParticipantDigestService, never()) - .recordVerifiedDigests( - any(String.class), any(PublishType.class), any(String.class), any(List.class)); - verify(recordedParticipantDigestService, never()) - .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); - verify(publishAttemptService, never()).executeFullVersionTransaction(any()); - verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); - verify(publishAttemptService, never()) - .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); + assertNoPublicationWrites(); } @Test @@ -750,14 +605,6 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("SUCCEEDED", snapshot.status()); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); @@ -788,73 +635,238 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { assertEquals("FAILED", snapshot.status()); assertEquals("PUBLISH_FAILED", snapshot.failureCode()); assertEquals("legacy publish failure", snapshot.failureMessage()); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); verify(publishAttemptService, never()).executeFullVersionTransaction(any()); } @Test - void uncertainAssetExportRemainsPendingForExactRetry() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + void selectedFailedReplayRequiresTheExactNoPublicationSeal() { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = selectedAttempt(reservation, request, 1); + attempt.setStatus(PublishAttemptStatus.FAILED); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) .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()); - when(assetExportService.exportAssets("tenant-1", 1)) - .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); - - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - assertTrue(thrown.getMessage().contains("asset export outcome is pending")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService, never()) - .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + assertEquals("FAILED", service.reconcileFullVersionPublish(request).status()); + verify(publishAttemptRepository).requireNoPublicationOperation(attempt); + org.mockito.Mockito.doThrow( + new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED")) + .when(publishAttemptRepository) + .requireNoPublicationOperation(attempt); + assertThrows(IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); } @Test - void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - 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()); - when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) - .thenThrow(new IllegalStateException("stage commit outcome is unknown")); + void nonCanonicalLegacyFullWorkflowFailsBeforeCompatibilityRewrite() { + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, "legacy-random-workflow"); + attempt.setId(101L); + attempt.setRequestDigest(null); + + assertThrows( + IllegalArgumentException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "legacy-random-workflow"))); + + verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); + } + + @Test + void missingLegacyPublishRequestIdIsRecoveredFromCanonicalWorkflowId() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.FAILED, 10L, 1, workflowId); + attempt.setRequestDigest(null); + attempt.setFailureCode("PUBLISH_FAILED"); + attempt.setFailureMessage("legacy publish failure"); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + + PublishWorkflowSnapshot snapshot = + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", null, workflowId)); + + assertEquals("FAILED", snapshot.status()); + assertEquals("PUBLISH_FAILED", snapshot.failureCode()); + verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); + } + + @Test + void missingLegacyPublishRequestIdDoesNotCrossTenantWorkflowPrefix() { + String workflowId = "publish:tenant-2:publish-request:workflow-1"; + + assertThrows( + IllegalArgumentException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", null, workflowId))); + + verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); + } + + @Test + void mismatchedRequestDigestCannotReplaySucceededAttempt() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); + attempt.setRequestDigest("0".repeat(64)); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + + assertThrows( + IllegalStateException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(publishedReleaseBundleService, never()) + .findPublishedReleaseBundle(any(String.class), any(Long.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + VersionAssetArtifactStateDto exportedState = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenReturn(staged); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn(exportedState); + org.mockito.Mockito.doThrow(new IllegalStateException("bundle commit outcome is unknown")) + .when(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(versionAssetArtifactService).stageExport("tenant-1", 10L, 1, workflowId); + assertTrue(thrown.getMessage().contains("incomplete evidence")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @ParameterizedTest + @EnumSource( + value = Status.Code.class, + names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code statusCode) { + SelectedPublishFixture fixture = selectedPublishFixture(1); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request())); + + assertTrue(thrown.getMessage().contains("temporarily unavailable")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void uncertainAssetExportRemainsPendingForExactRetry() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenReturn(staged); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)) + .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("asset export outcome remains unresolved")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + @Test + void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenThrow(new IllegalStateException("stage commit outcome is unknown")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("asset export intent commit requires exact readback")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 1, request.publishWorkflowId()); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(versionAssetArtifactService, never()) .markExportedUnattested( @@ -869,7 +881,8 @@ void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class)); + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); verify(versionAssetArtifactService, never()) .markFailed( any(String.class), @@ -889,9 +902,9 @@ void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() @Test void readbackWithArtifactButNoBundleRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -905,9 +918,6 @@ void readbackWithArtifactButNoBundleRemainsPartial() { null, LocalDateTime.now(), List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); @@ -915,9 +925,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("incomplete")); verify(publishAttemptService, never()).executeFullVersionTransaction(any()); @@ -928,71 +936,83 @@ void readbackWithArtifactButNoBundleRemainsPartial() { } @Test - void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); - List participantDigests = participantDigests(); - PublishedReleaseBundleDto bundle = - publishedReleaseBundleDto( - 1L, + void selectedStagedArtifactWithMismatchedWorkflowRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( "tenant-1", 10L, 1, - "v1", - workflowId, - MANIFEST_HASH, - List.of("manifest.json"), - participantDigests, - "generation-revision", - false, + "STAGED", + 1L, null, - LocalDateTime.now()); + "other-workflow", + null, + null, + LocalDateTime.now(), + List.of()); + + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + } + + @Test + void selectedStagedArtifactWithMismatchedScopeRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 2, + "STAGED", + 1L, + null, + fixture.request().publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of()); + + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + } + + @Test + void selectedStagedArtifactForPublishedVersionRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + fixture.version().setVersionState(VersionLifecycleState.PUBLISHED); + fixture.version().setVersionStateEpoch(2L); + VersionAssetArtifactStateDto artifact = stagedArtifact(fixture.request(), fixture.version()); + + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + } + + @Test + void selectedStagedArtifactWithMismatchedExportCandidateRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, 1, - "PUBLISHED", - 2L, + "STAGED", + 1L, MANIFEST_HASH, - workflowId, + request.publishWorkflowId(), null, null, LocalDateTime.now(), List.of("manifest.json")); - Game game = new Game(); - game.setTenantId("tenant-1"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) - .thenReturn(Optional.of(bundle)); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); - - PublishWorkflowRequest request = - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId); - PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublishMechanics(request); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(null); - assertEquals("SUCCEEDED", snapshot.status()); - verify(publishGateService) - .assertGatePassed( - any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); - verify(recordedParticipantDigestService) - .assertMatchesRecordedDigests("tenant-1", PublishType.FULL_VERSION, participantDigests); - verify(recordedParticipantDigestService) - .recordVerifiedDigests( - "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); - verify(publishAttemptService).markFullVersionSucceeded(workflowId); + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); } @Test - void exactPersistedStagedCandidateRequiresReconciliationBeforeRetry() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + void selectedStagedArtifactWithExactPersistedCandidateRetriesWithoutTreatingItAsPublished() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); VersionAssetArtifactStateDto stagedCandidate = new VersionAssetArtifactStateDto( "tenant-1", @@ -1001,127 +1021,173 @@ void exactPersistedStagedCandidateRequiresReconciliationBeforeRetry() { "STAGED", 2L, MANIFEST_HASH, - workflowId, + request.publishWorkflowId(), null, null, LocalDateTime.now(), List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + ExportedAssetManifest candidate = exportedManifest(List.of("manifest.json")); when(versionAssetArtifactService.findState("tenant-1", 10L)) .thenReturn(Optional.of(stagedCandidate)); - when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(candidate); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)) + .thenThrow(new AssetExportOutcomePendingException("exact export readback is unavailable")); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertTrue(thrown.getMessage().contains("incomplete")); + assertTrue(thrown.getMessage().contains("asset export outcome remains unresolved")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); - verify(publishGateService, never()) - .collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); } @Test - void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - VersionAssetArtifactStateDto emptyStagedArtifact = + void selectedStagedCandidateRetryAttestsTheExactFullManifestBeforeSuccess() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); + Version version = fixture.version(); + String workflowId = request.publishWorkflowId(); + List participantDigests = participantDigests(); + ExportedAssetManifest candidate = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto stagedCandidate = new VersionAssetArtifactStateDto( "tenant-1", - 10L, - 1, + version.getId(), + version.getVersionNumber(), "STAGED", - 1L, + 2L, + candidate.manifestHash(), + workflowId, null, + null, + LocalDateTime.now(), + candidate.requiredManifestAssetKeys()); + VersionAssetArtifactStateDto exportedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + version.getId(), + version.getVersionNumber(), + "EXPORTED_UNATTESTED", + 3L, + candidate.manifestHash(), workflowId, null, null, LocalDateTime.now(), - List.of()); - VersionAssetArtifactStateDto candidateStagedArtifact = + candidate.requiredManifestAssetKeys()); + VersionAssetArtifactStateDto publishedArtifact = new VersionAssetArtifactStateDto( "tenant-1", - 10L, - 1, - "STAGED", - 2L, - MANIFEST_HASH, + version.getId(), + version.getVersionNumber(), + "PUBLISHED", + 4L, + candidate.manifestHash(), workflowId, null, null, LocalDateTime.now(), - List.of("manifest.json")); - Game game = new Game(); - game.setTenantId("tenant-1"); - AtomicBoolean possibleObjectWrite = new AtomicBoolean(); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.of(emptyStagedArtifact), Optional.of(candidateStagedArtifact)); - org.mockito.Mockito.doReturn(null, manifest) - .when(versionAssetArtifactService) - .getExportCandidate("tenant-1", 10L); + candidate.requiredManifestAssetKeys()); + PublishedReleaseBundleDto bundle = + publishedReleaseBundleDto( + 1L, + "tenant-1", + version.getId(), + version.getVersionNumber(), + "v1", + workflowId, + candidate.manifestHash(), + candidate.requiredManifestAssetKeys(), + participantDigests, + "generation-revision", + false, + null, + LocalDateTime.now()); + when(versionAssetArtifactService.findState("tenant-1", version.getId())) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", version.getId())) + .thenReturn(candidate); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); - org.mockito.Mockito.doAnswer( - ignored -> { - // The exporter can fail after writing one or more immutable objects. - possibleObjectWrite.set(true); - throw new IllegalStateException( - "IMMUTABLE_OBJECT_CONFLICT: existing object differs from the candidate bytes"); - }) - .when(assetExportService) - .exportAssets("tenant-1", 1); + .thenReturn(participantDigests); + when(assetExportService.exportAssets("tenant-1", version.getVersionNumber())) + .thenReturn(candidate); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + "tenant-1", version.getId(), version.getVersionNumber(), workflowId, candidate)) + .thenReturn(exportedArtifact); + when(publishedReleaseBundleService.createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + org.mockito.ArgumentMatchers.eq(candidate), + any(String.class), + org.mockito.ArgumentMatchers.eq(participantDigests), + same(capturedWorldPublicationEvidence))) + .thenReturn(bundle); + when(versionAssetArtifactService.markPublished( + "tenant-1", + version.getId(), + exportedArtifact.stateEpoch(), + workflowId, + candidate.manifestHash())) + .thenReturn(publishedArtifact); - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); - assertTrue(thrown.getMessage().contains("failure marking")); - assertTrue(possibleObjectWrite.get()); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(assetExportService).exportAssets("tenant-1", 1); + assertEquals("SUCCEEDED", snapshot.status(), snapshot.toString()); + verify(versionAssetArtifactService, org.mockito.Mockito.times(2)) + .getExportCandidate("tenant-1", version.getId()); verify(versionAssetArtifactService, never()) - .markFailed( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class), + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(versionAssetArtifactService) + .markExportedUnattested( + "tenant-1", version.getId(), version.getVersionNumber(), workflowId, candidate); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + org.mockito.ArgumentMatchers.eq(candidate), any(String.class), - any(String.class)); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService, never()) - .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + org.mockito.ArgumentMatchers.eq(participantDigests), + same(capturedWorldPublicationEvidence)); + verify(publishAttemptService).markFullVersionSucceeded(workflowId); + verify(publishAttemptRepository).sealPublication(attempt, true); } @Test - void mismatchedPersistedStagedCandidateRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - VersionAssetArtifactStateDto stagedCandidate = + void selectedStagedArtifactWithMismatchedPersistedCandidateKeysRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, @@ -1129,39 +1195,23 @@ void mismatchedPersistedStagedCandidateRemainsPartial() { "STAGED", 2L, MANIFEST_HASH, - workflowId, + request.publishWorkflowId(), null, null, LocalDateTime.now(), List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.of(stagedCandidate)); when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) .thenReturn(exportedManifest(List.of("different.json"))); - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - - assertTrue(thrown.getMessage().contains("incomplete")); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(publishAttemptService, never()).executeFullVersionTransaction(any()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); } @Test - void malformedPersistedStagedCandidateReadbackRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - VersionAssetArtifactStateDto stagedCandidate = + void selectedStagedArtifactWithMismatchedPersistedCandidateHashRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, @@ -1169,38 +1219,28 @@ void malformedPersistedStagedCandidateReadbackRemainsPartial() { "STAGED", 2L, MANIFEST_HASH, - workflowId, + request.publishWorkflowId(), null, null, LocalDateTime.now(), List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.of(stagedCandidate)); when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) - .thenThrow(new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE")); - - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + .thenReturn( + new ExportedAssetManifest( + "sha256:" + "c".repeat(64), + 1, + List.of("manifest.json"), + artifactDigests(List.of("manifest.json")))); - assertTrue(thrown.getMessage().contains("incomplete")); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(publishAttemptService, never()).executeFullVersionTransaction(any()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); } @Test - void mismatchedStagedArtifactWorkflowRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - assertStagedArtifactRemainsPartial( - VersionLifecycleState.DRAFT, + void selectedStagedArtifactWithUncertainPersistedCandidateRemainsPartial() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, @@ -1208,144 +1248,137 @@ void mismatchedStagedArtifactWorkflowRemainsPartial() { "STAGED", 2L, MANIFEST_HASH, - "other-workflow", + request.publishWorkflowId(), null, null, LocalDateTime.now(), - List.of("manifest.json"))); + List.of("manifest.json")); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenThrow(new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE")); + + assertSelectedStagedArtifactRemainsPartial(fixture, artifact); + verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); + } + + private void assertSelectedStagedArtifactRemainsPartial( + SelectedPublishFixture fixture, VersionAssetArtifactStateDto artifact) { + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request())); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); } @Test - void mismatchedStagedArtifactScopeRemainsPartial() { - assertStagedArtifactRemainsPartial( - VersionLifecycleState.DRAFT, - new VersionAssetArtifactStateDto( + void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + PublishAttempt attempt = fixture.attempt(); + Version version = fixture.version(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(2L); + List participantDigests = participantDigests(); + PublishedReleaseBundleDto bundle = + publishedReleaseBundleDto( + 1L, "tenant-1", 10L, - 2, - "STAGED", - 2L, + 1, + "v1", + workflowId, MANIFEST_HASH, - "publish:tenant-1:publish-request:workflow-1", - null, + List.of("manifest.json"), + participantDigests, + "generation-revision", + false, null, - LocalDateTime.now(), - List.of("manifest.json"))); - } - - @Test - void stagedArtifactForPublishedVersionRemainsPartial() { - assertStagedArtifactRemainsPartial( - VersionLifecycleState.PUBLISHED, + LocalDateTime.now()); + VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, 1, - "STAGED", - 1L, - null, - "publish:tenant-1:publish-request:workflow-1", + "PUBLISHED", + 2L, + MANIFEST_HASH, + workflowId, null, null, LocalDateTime.now(), - List.of())); - } - - private void assertStagedArtifactRemainsPartial( - VersionLifecycleState versionState, VersionAssetArtifactStateDto artifact) { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, versionState); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + List.of("manifest.json")); when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) - .thenReturn(exportedManifest(List.of("manifest.json"))); + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("manifest.json"), + artifactDigests(List.of("manifest.json")))); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); - assertTrue(thrown.getMessage().contains("incomplete")); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + assertEquals("SUCCEEDED", snapshot.status()); + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests("tenant-1", PublishType.FULL_VERSION, participantDigests); + verify(recordedParticipantDigestService) + .recordVerifiedDigests( + "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); + verify(publishAttemptService).markFullVersionSucceeded(workflowId); + verify(publishAttemptRepository).sealPublication(attempt, true); } @Test - void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - attempt.setId(101L); - attempt.setRequestDigest(null); + void selectedAttemptWithMismatchedVersionEvidenceIsNotRewritten() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); 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.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - assertEquals(null, attempt.getRequestDigest()); + assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } @Test - void legacyFullMixedScopeAttemptIsNotRebound() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - attempt.setId(101L); - attempt.setRequestDigest(null); + void selectedFullAttemptWithMixedScopeIsNotRebound() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); 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.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - assertEquals(null, attempt.getRequestDigest()); + assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } @Test void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); attempt.setScriptPatchVersion("legacy-patch"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(publishedReleaseBundleService, never()) @@ -1353,91 +1386,27 @@ void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { } @Test - void nonCanonicalLegacyFullWorkflowFailsBeforeCompatibilityRewrite() { - PublishAttempt attempt = - fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, "legacy-random-workflow"); - attempt.setId(101L); - attempt.setRequestDigest(null); - - assertThrows( - IllegalArgumentException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "legacy-random-workflow"))); - - verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - } - - @Test - void missingLegacyPublishRequestIdIsRecoveredFromCanonicalWorkflowId() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.FAILED, 10L, 1, workflowId); - attempt.setRequestDigest(null); - attempt.setFailureCode("PUBLISH_FAILED"); - attempt.setFailureMessage("legacy publish failure"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", null, workflowId)); - - assertEquals("FAILED", snapshot.status()); - assertEquals("PUBLISH_FAILED", snapshot.failureCode()); - verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); - } - - @Test - void missingLegacyPublishRequestIdDoesNotCrossTenantWorkflowPrefix() { - String workflowId = "publish:tenant-2:publish-request:workflow-1"; - - assertThrows( - IllegalArgumentException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", null, workflowId))); - - verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); - } - - @Test - void mismatchedRequestDigestCannotReplaySucceededAttempt() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); - attempt.setRequestDigest("0".repeat(64)); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - - verify(publishedReleaseBundleService, never()) - .findPublishedReleaseBundle(any(String.class), any(Long.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - - @Test - void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - Game game = new Game(); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + void postBundleFailureAfterRollbackLeavesAttemptPendingWithoutCleaningAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + Version version = fixture.version(); + String workflowId = request.publishWorkflowId(); List participantDigests = participantDigests(); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, version); + VersionAssetArtifactStateDto exportedState = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); PublishedReleaseBundleDto bundle = publishedReleaseBundleDto( 1L, @@ -1453,9 +1422,11 @@ void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { false, null, LocalDateTime.now()); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests); @@ -1486,25 +1457,11 @@ void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + same(capturedWorldPublicationEvidence))) .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - VersionAssetArtifactStateDto stagedArtifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "STAGED", - 1L, - null, - workflowId, - null, - null, - LocalDateTime.now(), - List.of()); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.empty(), Optional.of(stagedArtifact)); org.mockito.Mockito.doAnswer( invocation -> { // The production transaction rolls managed entity changes back before readback. @@ -1515,29 +1472,34 @@ void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { .when(versionRepository) .save(any(Version.class)); - PublishWorkflowRequest request = - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId); - PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublishMechanics(request); + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertEquals("FAILED", snapshot.status()); - verify(publishAttemptService) + assertTrue(thrown.getMessage().contains("incomplete evidence")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } @Test void finalizationFailureWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - 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()); @@ -1553,15 +1515,13 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); assertEquals(1, readFailure.getSuppressed().length); assertEquals(operationFailure, readFailure.getSuppressed()[0]); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1569,63 +1529,32 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @ParameterizedTest - @EnumSource( - 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); - 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))) - .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); - - IllegalStateException thrown = - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - - assertTrue(thrown.getMessage().contains("temporarily unavailable")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - @Test void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - 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()); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); org.mockito.Mockito.doThrow(new IllegalStateException("commit outcome unknown")) .when(publishAttemptService) .executeFullVersionTransaction(any()); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1635,15 +1564,17 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { @Test void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - 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()); @@ -1658,15 +1589,13 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); assertEquals(1, readFailure.getSuppressed().length); assertEquals(ambiguousCommit, readFailure.getSuppressed()[0]); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1675,32 +1604,20 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { } @Test - void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - Game game = new Game(); - game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + void preExportFailureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); - when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); - when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) - .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); - java.util.concurrent.atomic.AtomicInteger transactionCalls = - new java.util.concurrent.atomic.AtomicInteger(); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, + "recorded digest mismatch")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); org.mockito.Mockito.doAnswer( invocation -> { - if (transactionCalls.getAndIncrement() == 0) { - throw new PublishAttemptService.FullVersionTransactionException( - new IllegalStateException("version finalization failed")); - } ((java.util.function.Supplier) invocation.getArgument(0)).get(); throw new IllegalStateException("failure-marking commit outcome unknown"); }) @@ -1710,50 +1627,1146 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublishMechanics( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + .markFullVersionFailed( + request.publishWorkflowId(), + "RECORDED_CONTENT_DIGEST_MISMATCH", + "recorded digest mismatch"); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(assetExportService, never()) .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - private PublishAttempt fullAttempt( - PublishAttemptStatus status, long versionId, int versionNumber, String workflowId) { - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(versionId); - attempt.setVersionNumber(versionNumber); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId(workflowId); - attempt.setStatus(status); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", String.valueOf(versionId), "workflow-1") - .requestDigest()); - return attempt; - } - - private Version fullVersion(long versionId, int versionNumber, VersionLifecycleState state) { - Version version = new Version(); - version.setId(versionId); - version.setTenantId("tenant-1"); - version.setVersionNumber(versionNumber); - version.setVersionState(state); - version.setVersionStateEpoch(state == VersionLifecycleState.PUBLISHED ? 2L : 1L); - version.setUpdatedAt(LocalDateTime.now()); - return version; + @Test + void failureMarkingReadbackFailureKeepsPendingContractAndOriginalFailure() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + IllegalStateException operationFailure = new IllegalStateException("failure mark uncertain"); + IllegalStateException readFailure = new IllegalStateException("publication read failed"); + 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, + "recorded digest mismatch")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.empty()) + .thenThrow(readFailure); + org.mockito.Mockito.doThrow( + new PublishAttemptService.FullVersionTransactionException(operationFailure)) + .when(publishAttemptService) + .executeFullVersionTransaction(any()); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("failure marking readback failed")); + assertEquals(readFailure, thrown.getCause()); + assertEquals(1, readFailure.getSuppressed().length); + assertEquals(operationFailure, readFailure.getSuppressed()[0]); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + @Test + void freshFullVersionPublishIsDeniedBeforeAnyMutation() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException freshDenial = + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE, + freshDenial.errorCode()); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE + + ": " + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException + .SAFE_MESSAGE, + freshDenial.getMessage()); + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); + + verify(publishAttemptRepository, org.mockito.Mockito.times(2)) + .findByPublishWorkflowId(workflowId); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId))); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(publishedReleaseBundleService, never()) + .findPublishedReleaseBundle(any(String.class), any(Long.class)); + verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { + SelectedPublishFixture fixture = selectedPublishFixture(8); + Version version = fixture.version(); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); + List participantDigests = participantDigests(); + ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, version); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 8, request.publishWorkflowId())) + .thenReturn(staged); + when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 8, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("logo.png", "manifest.json"))); + when(publishedReleaseBundleService.createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence))) + .thenReturn( + publishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 8, + "v1", + request.publishWorkflowId(), + MANIFEST_HASH, + List.of("logo.png", "manifest.json"), + participantDigests, + "genrev-tenant-1-10", + false, + null, + LocalDateTime.now())); + when(versionAssetArtifactService.markPublished( + any(String.class), + any(Long.class), + any(Long.class), + any(String.class), + any(String.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 8, + "PUBLISHED", + 3L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("logo.png", "manifest.json"))); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); + + assertEquals("SUCCEEDED", snapshot.status()); + assertEquals(10L, snapshot.versionId()); + assertEquals(VersionLifecycleState.PUBLISHED, version.getVersionState()); + assertEquals(2L, version.getVersionStateEpoch()); + verify(versionRepository, never()).findTopByTenantIdOrderByVersionNumberDesc("tenant-1"); + verify(versionRepository).save(version); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService) + .recordFullVersionParticipantDigests(request.publishWorkflowId(), participantDigests); + verify(publishAttemptRepository).requirePublicationPending(attempt); + verify(publishAttemptRepository).sealPublication(attempt, true); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + + InOrder publishOrder = + inOrder( + publishGateService, + recordedParticipantDigestService, + versionAssetArtifactService, + assetExportService, + publishedReleaseBundleService, + publishAttemptService, + publishAttemptRepository); + publishOrder + .verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(PublishType.FULL_VERSION), + org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 8, request.publishWorkflowId()); + publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); + publishOrder + .verify(publishAttemptService) + .recordFullVersionParticipantDigests( + org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()), + org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + publishOrder.verify(publishAttemptRepository).sealPublication(attempt, true); + } + + @Test + void privateMechanicsRecordsTypedPublishGateFailures() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + 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, + "recorded digest mismatch")) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); + verify(publishAttemptService) + .markFullVersionFailed( + org.mockito.ArgumentMatchers.eq(fixture.request().publishWorkflowId()), + org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), + org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + List participantDigests = participantDigests(); + 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)); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); + verify(publishAttemptService, never()) + .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + } + + @Test + void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), + Optional.of(staged), + Optional.of(stagedCandidate), + Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(null, manifest, manifest); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenReturn(staged); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + org.mockito.Mockito.doThrow(new IllegalStateException("attestation write outcome is unknown")) + .when(versionAssetArtifactService) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue( + thrown.getMessage().contains("exported candidate requires exact retry/reconciliation")); + assertEquals("attestation write outcome is unknown", thrown.getCause().getMessage()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService) + .markExportedUnattested( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(10L), + org.mockito.ArgumentMatchers.eq(1), + org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()), + same(manifest)); + verify(versionAssetArtifactService, org.mockito.Mockito.times(4)) + .getExportCandidate("tenant-1", 10L); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @Test + void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Exception { + SelectedPublishFixture fixture = selectedPublishFixture(1); + SelectionSnapshot seedReservation = fixture.reservation(); + AuthoredDraftPublishSelection seedSelection = seedReservation.selection(); + DraftCommitBinding seedCommit = seedSelection.selectedCommit(); + DraftCommitBinding expandedCommit = + PublishedWorldSelectorFixtures.withIsolatedFreshWorldGraph(seedCommit); + List graphRevisions = new java.util.ArrayList<>(); + for (RevisionPayload revision : expandedCommit.revisions()) { + if (seedCommit.revisions().contains(revision)) continue; + graphRevisions.add( + new RevisionPayload( + Integer.toString(graphRevisions.size()), + revision.revisionId(), + revision.owner(), + revision.payload())); + } + List graphAffectedUnits = + expandedCommit.affectedUnits().stream() + .filter(unit -> !seedCommit.affectedUnits().contains(unit)) + .toList(); + DraftCommitBinding typedCommit = + DraftCommitBinding.create( + seedCommit.target(), + seedCommit.requestId(), + seedCommit.commitId(), + seedCommit.baseCommitId(), + graphRevisions, + graphAffectedUnits); + PublishIntent seedIntent = seedSelection.intent(); + PublishIntent typedIntent = + new PublishIntent( + seedIntent.canonicalTenantId(), + seedIntent.canonicalVersionId(), + seedIntent.publishRequestId(), + seedIntent.expectedVersionStateEpoch(), + seedIntent.notes(), + seedIntent.selectedCommitRequestId(), + seedIntent.selectedCommitId(), + typedCommit.digest()); + VisibilityFence typedFence = + new VisibilityFence( + seedSelection.target(), + seedSelection.fenceRequestId(), + seedSelection.fenceCommitId(), + typedCommit.digest(), + seedSelection.fenceResultVectorJson(), + OffsetDateTime.parse(seedSelection.fenceCreatedAt())); + SelectionSnapshot reservation = + new SelectionSnapshot( + AuthoredDraftPublishSelection.capture( + typedIntent, + seedSelection.target(), + new PublicationEvidence(typedCommit, typedFence)), + seedReservation.createdAt()); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = fixture.attempt(); + attempt.setRequestDigest(reservation.selection().digest()); + Version version = fixture.version(); + fixture = new SelectedPublishFixture(reservation, request, attempt, version); + when(authoredSelections.readByPublishRequest( + typedIntent.canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + String workflowId = request.publishWorkflowId(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(2L); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + // This fixture stipulates historical Account/APPLIED bytes; it proves no live owner authority. + WorldPublishedStartLocationEvidence fixtureEvidence = + PublishedWorldSelectorFixtures.evidence( + fixture.reservation().selection().target(), + fixture.reservation().selection().selectedCommit()); + WorldPublishedStartLocationEvidence.Request fixtureRequest = fixtureEvidence.request(); + WorldPublishedStartLocationEvidence selectedEvidence = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + fixtureRequest.targetNamespace(), + fixtureRequest.canonicalTenantId(), + fixtureRequest.canonicalVersionId(), + fixtureRequest.intakeRequestId(), + fixtureRequest.publicationFence(), + request.publishRequestId(), + fixtureRequest.requestDigest(), + Long.parseLong(request.intent().expectedVersionStateEpoch()), + workflowId, + fixtureRequest.appliedCommitId(), + fixtureRequest.contentDigest(), + fixtureRequest.digestSchemaVersion(), + fixtureRequest.worldAffectedTuples()), + fixtureEvidence.selectorReceiptBytes(), + fixtureEvidence.originalAccountBindingBytes(), + fixtureEvidence.appliedResultBytes()); + List participantDigests = + PublishedWorldSelectorFixtures.participants( + 10L, selectedEvidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + PublishedReleaseBundleDto bundle = + new PublishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v2", + workflowId, + MANIFEST_HASH, + List.of("manifest.json"), + participantDigests, + List.of(), + "generation-revision", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(List.of("manifest.json")), + selectedEvidence); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PUBLISHED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + Game game = new Game(); + game.setTenantId("tenant-1"); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); + + assertEquals("SUCCEEDED", snapshot.status()); + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests("tenant-1", PublishType.FULL_VERSION, participantDigests); + verify(recordedParticipantDigestService) + .recordVerifiedDigests( + "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); + verify(publishAttemptService).markFullVersionSucceeded(workflowId); + } + + @Test + void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + PublishAttempt attempt = fixture.attempt(); + Version version = fixture.version(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto emptyStagedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.now(), + List.of()); + VersionAssetArtifactStateDto candidateStagedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + Game game = new Game(); + game.setTenantId("tenant-1"); + AtomicBoolean possibleObjectWrite = new AtomicBoolean(); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(emptyStagedArtifact), Optional.of(candidateStagedArtifact)); + org.mockito.Mockito.doReturn(null, manifest) + .when(versionAssetArtifactService) + .getExportCandidate("tenant-1", 10L); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + org.mockito.Mockito.doAnswer( + ignored -> { + // The exporter can fail after writing one or more immutable objects. + possibleObjectWrite.set(true); + throw new IllegalStateException( + "IMMUTABLE_OBJECT_CONFLICT: existing object differs from the candidate bytes"); + }) + .when(assetExportService) + .exportAssets("tenant-1", 1); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("candidate/write reconciliation")); + assertTrue(possibleObjectWrite.get()); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService, never()) + .markFailed( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + @Test + void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + Version version = fixture.version(); + String workflowId = request.publishWorkflowId(); + List participantDigests = participantDigests(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, version); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + PublishedReleaseBundleDto bundle = + publishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v1", + workflowId, + MANIFEST_HASH, + List.of("manifest.json"), + participantDigests, + "generation-revision", + false, + null, + LocalDateTime.now()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), + Optional.of(staged), + Optional.of(stagedCandidate), + Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(null, manifest, manifest); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 3L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json"))); + when(publishedReleaseBundleService.createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence))) + .thenReturn(bundle); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.empty()); + org.mockito.Mockito.doAnswer( + invocation -> { + // The production transaction rolls managed entity changes back before readback. + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + throw new IllegalStateException("version finalization failed"); + }) + .when(versionRepository) + .save(any(Version.class)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue( + thrown.getMessage().contains("exported candidate requires exact retry/reconciliation")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); + assertEquals(1L, version.getVersionStateEpoch()); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService) + .markExportedUnattested( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(10L), + org.mockito.ArgumentMatchers.eq(1), + org.mockito.ArgumentMatchers.eq(workflowId), + same(manifest)); + verify(versionAssetArtifactService, org.mockito.Mockito.times(4)) + .getExportCandidate("tenant-1", 10L); + verify(versionRepository).save(version); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + same(manifest), + any(String.class), + org.mockito.ArgumentMatchers.eq(participantDigests), + same(capturedWorldPublicationEvidence)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(same(fixture.attempt()), org.mockito.ArgumentMatchers.anyBoolean()); + verify(versionAssetArtifactService, never()) + .markFailed( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + private PublishAttempt fullAttempt( + PublishAttemptStatus status, long versionId, int versionNumber, String workflowId) { + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId("tenant-1"); + attempt.setVersionId(versionId); + attempt.setVersionNumber(versionNumber); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setPublishWorkflowId(workflowId); + attempt.setStatus(status); + attempt.setRequestDigest( + PublicationDigestRequestBinding.full("tenant-1", String.valueOf(versionId), "workflow-1") + .requestDigest()); + return attempt; + } + + private PublishIntent selectedIntent() { + return selectedReservation().selection().intent(); + } + + private SelectionSnapshot selectedReservation() { + UUID requestId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID commitId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-1", + List.of( + new RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "1"))); + PublishIntent intent = + new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "workflow-1", + "1", + "notes", + requestId, + commitId, + binding.digest()); + VisibilityFence fence = + new VisibilityFence( + target, + requestId, + commitId, + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + // This fixture selects an existing intent for the private conditional mechanics seam; it + // carries no Account authorization or authenticated World publication freeze. + return new SelectionSnapshot(selection, OffsetDateTime.parse("2026-10-08T00:00:00Z")); + } + + private PublishWorkflowRequest selectedRequest(SelectionSnapshot reservation) { + PublishIntent intent = reservation.selection().intent(); + return new PublishWorkflowRequest( + "tenant-1", + intent.notes(), + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + intent); + } + + private PublishAttempt selectedAttempt( + SelectionSnapshot reservation, PublishWorkflowRequest request, int versionNumber) { + PublishAttempt attempt = + fullAttempt( + PublishAttemptStatus.PENDING, + reservation.selection().target().gameDesignVersionRowId(), + versionNumber, + request.publishWorkflowId()); + attempt.setRequestDigest(reservation.selection().digest()); + return attempt; + } + + private SelectedPublishFixture selectedPublishFixture(int versionNumber) { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = selectedAttempt(reservation, request, versionNumber); + Version version = fullVersion(10L, versionNumber, VersionLifecycleState.DRAFT); + version.setNotes("notes"); + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(publishAttemptRepository.findByPublishWorkflowIdForUpdate(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 10L)) + .thenReturn(Optional.of(version)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + return new SelectedPublishFixture(reservation, request, attempt, version); + } + + private SelectedSucceededReplayFixture selectedSucceededReplayFixture( + VersionLifecycleState lifecycleState) throws Exception { + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + // Stipulated original upstream bytes, not live Account or World producer proof. This closed + // operation carries one typed World graph, reviewed base, selection, and publication request. + var operation = + IsolatedPublicationOperationFixtures.fresh( + target, "genesis:66666666-6666-4666-8666-666666666666"); + var selected = operation.account().input().selection(); + SelectionSnapshot reservation = + new SelectionSnapshot( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, request.publishWorkflowId()); + attempt.setRequestDigest(reservation.selection().digest()); + Version version = fullVersion(10L, 1, lifecycleState); + version.setVersionStateEpoch( + switch (lifecycleState) { + case PUBLISHED -> 6L; + case ACTIVE -> 7L; + case RETIRED -> 8L; + default -> + throw new IllegalArgumentException("terminal replay fixture requires a release"); + }); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + + // The retained v2 selector payload must bind to the exact selected World commit and original + // publication request, regardless of the Version's later legal lifecycle state. + WorldPublishedStartLocationEvidence selectedEvidence = operation.world(); + List participantDigests = + PublishedWorldSelectorFixtures.participants( + 10L, selectedEvidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + PublishedReleaseBundleDto bundle = + new PublishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v2", + request.publishWorkflowId(), + MANIFEST_HASH, + List.of("manifest.json"), + participantDigests, + List.of(), + "generation-revision", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(List.of("manifest.json")), + selectedEvidence); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PUBLISHED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); + return new SelectedSucceededReplayFixture( + request, attempt, bundle, participantDigests, artifact); + } + + private void assertNoPublicationWrites() { + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(versionAssetArtifactService, never()) + .markPublished( + any(String.class), + any(Long.class), + any(Long.class), + any(String.class), + any(String.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(recordedParticipantDigestService, never()) + .recordVerifiedDigests( + any(String.class), any(PublishType.class), any(String.class), any(List.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + } + + private static PublishedReleaseBundleDto withWorkflowId( + PublishedReleaseBundleDto bundle, String workflowId) { + return new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + bundle.attestationSchemaVersion(), + workflowId, + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + bundle.worldPublishedStartLocationEvidence()); + } + + private VersionAssetArtifactStateDto stagedArtifact( + PublishWorkflowRequest request, Version version) { + return new VersionAssetArtifactStateDto( + "tenant-1", + version.getId(), + version.getVersionNumber(), + "STAGED", + 1L, + null, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of()); + } + + private PublishWorkflowSnapshot reflectiveUnitHarnessReconcileSelectedPublicationMechanics( + PublishWorkflowRequest request) { + try { + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileSelectedPublicationMechanics", PublishWorkflowRequest.class); + mechanics.setAccessible(true); + return (PublishWorkflowSnapshot) mechanics.invoke(service, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) throw runtimeException; + if (cause instanceof Error error) throw error; + throw new AssertionError("selected publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("selected publication mechanics harness is unavailable", exception); + } + } + + private Version fullVersion(long versionId, int versionNumber, VersionLifecycleState state) { + Version version = new Version(); + version.setId(versionId); + version.setTenantId("tenant-1"); + version.setVersionNumber(versionNumber); + version.setVersionState(state); + version.setVersionStateEpoch(state == VersionLifecycleState.PUBLISHED ? 2L : 1L); + version.setUpdatedAt(LocalDateTime.now()); + return version; } private List participantDigests() { return List.of( new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest", 1, null, null)); + "GAME_DESIGN_CONTROL_PLANE", + "10", + selectedIntent().selectedCommitId().toString(), + "digest", + 1, + null, + null)); } + private record SelectedPublishFixture( + SelectionSnapshot reservation, + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version) {} + + private record SelectedSucceededReplayFixture( + PublishWorkflowRequest request, + PublishAttempt attempt, + PublishedReleaseBundleDto bundle, + List participantDigests, + VersionAssetArtifactStateDto artifact) {} + private static ExportedAssetManifest exportedManifest(List usageKeys) { return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); } 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 5b3c2abfc9..721d120931 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 @@ -21,6 +21,7 @@ import java.util.function.Supplier; 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; @@ -93,6 +94,18 @@ class VersionServiceImplTest { private VersionServiceImpl service; + private static PublishIntent selectedIntent() { + return new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISH_REQUEST_ID, + "1", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); + } + @BeforeEach void setup() throws Exception { MockitoAnnotations.openMocks(this); @@ -132,39 +145,24 @@ void setup() throws Exception { } @Test - void publishVersionDelegatesToCommandServiceAndReturnsItsResult() throws Exception { - when(publishCommandService.publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.eq( - "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID))) - .thenReturn( - new VersionDto( - 10L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now())); - - VersionDto dto = service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + void publishVersionRequiresCurrentAuthorizationAndOwnerFreeze() { + IllegalStateException thrown = + assertThrows(IllegalStateException.class, () -> service.publishVersion(selectedIntent())); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); - verify(publishCommandService) + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")); + verify(publishCommandService, org.mockito.Mockito.never()).reserveSelection(any()); + verify(publishCommandService, org.mockito.Mockito.never()) .publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.eq( - "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); + any(String.class), any(String.class), any(String.class), any(String.class)); + org.mockito.Mockito.verifyNoInteractions(temporalPublishOrchestrator); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .assertGatePassed(any(VersionDto.class), any(List.class)); } @Test @@ -245,63 +243,37 @@ void versionStateSameStateRequestRemainsAReadOnlyNoOp() { } @Test - void publishVersionPropagatesFreshPublicationDenialBeforeMutation() { + void legacyFullVersionRequestOnlyDelegatesToRetainedTerminalReplay() throws Exception { + VersionDto expected = + new VersionDto( + 10L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); when(publishCommandService.publishFullVersion( "tenant-1", "notes", PUBLISH_REQUEST_ID, "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)) - .thenThrow( - new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); - - assertThrows( - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, - () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); - - verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); - verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); - verify(publishGateService, org.mockito.Mockito.never()) - .collectFullVersionParticipantDigests(any(VersionDto.class), any(), any()); - verify(assetExportService, org.mockito.Mockito.never()) - .exportAssets(any(String.class), any(Integer.class)); - } - - @Test - void publishVersionWithTemporalConfiguredPropagatesDenialBeforeLocalMutation() { - VersionServiceImpl temporalService = - new VersionServiceImpl( - versionRepository, - gameRepository, - publishedPluginVersionRepository, - pluginVersionStatusEventRepository, - Mappers.getMapper(VersionMapper.class), - scriptingClient, - publishAttemptService, - publishGateService, - controlPlaneDigestService, - versionAssetArtifactService, - publishedReleaseBundleService, - recordedParticipantDigestService, - pluginBundleIntakeService, - pluginBundleStorageService, - publishCommandService, - Optional.of(temporalPublishOrchestrator)); - when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) - .thenThrow( - new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + .thenReturn(expected); - assertThrows( - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, - () -> temporalService.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + VersionDto actual = service.replayLegacyFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); - verify(temporalPublishOrchestrator).publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); - verify(publishCommandService, org.mockito.Mockito.never()) + assertEquals(expected, actual); + verify(publishCommandService) .publishFullVersion( - any(String.class), any(String.class), any(String.class), any(String.class)); - verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); - verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); - verify(assetExportService, org.mockito.Mockito.never()) - .exportAssets(any(String.class), any(Integer.class)); + "tenant-1", + "notes", + PUBLISH_REQUEST_ID, + "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID); + org.mockito.Mockito.verifyNoInteractions(temporalPublishOrchestrator); } @Test @@ -998,27 +970,20 @@ private Version scriptPatchVersion( } @Test - void publishVersionPropagatesTypedPublishGateFailures() { - when(publishCommandService.publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.anyString())) - .thenThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")); - - PublishGateFailureException thrown = + void publishVersionCannotReachPublishGatesWithoutOwnerFreeze() { + IllegalStateException thrown = org.junit.jupiter.api.Assertions.assertThrows( - PublishGateFailureException.class, - () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + IllegalStateException.class, () -> service.publishVersion(selectedIntent())); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")); + verify(publishGateService, org.mockito.Mockito.never()).assertGatePassed(any(), any()); + verify(publishCommandService, org.mockito.Mockito.never()) + .publishFullVersion( + any(String.class), any(String.class), any(String.class), any(String.class)); } @Test - void publishVersionDeletesExportedAssetsWhenAttestationWriteFails() { + void publishVersionDoesNotStartTemporalWorkflowWithoutOwnerFreeze() { VersionServiceImpl temporalService = new VersionServiceImpl( versionRepository, @@ -1037,25 +1002,20 @@ void publishVersionDeletesExportedAssetsWhenAttestationWriteFails() { pluginBundleStorageService, publishCommandService, Optional.of(temporalPublishOrchestrator)); - 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())); - - VersionDto dto = temporalService.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> temporalService.publishVersion(selectedIntent())); - 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); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .assertGatePassed(any(VersionDto.class), any(List.class)); } @Test