From 9f909b6756a49908b35c4b358d8d00ed46af6330 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:46:43 +1300 Subject: [PATCH 1/9] Converge selected publication source owners and preserve StartSession receiving --- ...dmin-as-external-operator-write-ingress.md | 2 + .../game-design-service/api-contracts.md | 2 + .../game-design-service/asset-storage.md | 8 +- .../game-design-service/version-control.md | 8 +- .../logging-admin-service/api-contracts.md | 4 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 12 + .../common-platform-core/build.gradle.kts | 1 + .../common/gamedesign/AssetSnapshot.java | 166 +++ .../DraftSynchronizedVisibilityEvidence.java | 359 +++++ ...GameDesignPublicationOperationBinding.java | 118 +- ...electedDraftPublicationFreezeEvidence.java | 242 +++ ...dPublicationArtifactInventoryEvidence.java | 781 ++++++++++ ...DesignPublicationOperationBindingTest.java | 154 ++ ...lishedRealmEntryPolicySetEvidenceTest.java | 10 +- ...atedWorldPublicationInventoryFixtures.java | 201 +++ .../draft/GameDesignReviewedBaseEvidence.java | 14 +- .../GameDesignReviewedBaseRepository.java | 34 +- .../publication/AssetApplication.java | 44 + .../gamedesign/publication/AssetSnapshot.java | 110 ++ .../publication/AssetSourceRepository.java | 596 ++++++++ .../gamedesign/publication/CommandSource.java | 13 +- .../publication/CommandSourceRepository.java | 18 +- .../GameDesignPublicationOperation.java | 55 +- .../GameDesignSourceRepository.java | 197 ++- .../publication/RealmPolicySource.java | 3 +- .../VersionAssetPublicationRepository.java | 92 +- .../V1003__ordinary_asset_source.sql | 389 +++++ ...04__publication_operation_inventory_v2.sql | 291 ++++ .../migration/V1005__gameplay_rule_source.sql | 400 +++++ ..._draft_application_lifecycle_interlock.sql | 124 ++ .../V1007__branding_asset_source_history.sql | 495 +++++++ .../V1008__template_config_source_history.sql | 870 +++++++++++ ...elected_publication_game_logic_receipt.sql | 52 + ...cted_template_world_source_association.sql | 105 ++ ...ublication_control_plane_digest_schema.sql | 202 +++ ...d_template_references_and_tenant_phase.sql | 410 +++++ ...ected_inventory_asset_export_candidate.sql | 122 ++ ..._launch_descriptor_association_binding.sql | 219 +++ ...template_config_owner_source_inventory.sql | 365 +++++ ...template_config_owner_source_inventory.sql | 238 +++ ...ified_selected_publication_attestation.sql | 269 ++++ ...18__selected_inventory_closure_profile.sql | 66 + ..._release_original_account_owner_schema.sql | 23 + ...lected_full_semantic_owner_attestation.sql | 273 ++++ ...al_start_session_actor_core_projection.sql | 387 +++++ ..._release_original_account_owner_schema.sql | 23 + ...3__selected_export_artifact_projection.sql | 108 ++ ...V1024__asset_bound_reviewed_draft_base.sql | 184 +++ .../draft/IsolatedAssetSourceOwnerSetup.java | 63 + .../draft/IsolatedPublicationOwnerSetup.java | 130 +- .../IsolatedPublicationOperationFixtures.java | 28 +- ...meDesignSourcePostgresIntegrationTest.java | 121 ++ ...lmPolicySourcePostgresIntegrationTest.java | 13 + ...StorageUpgradePostgresIntegrationTest.java | 1320 +++++++++++++++++ ...ationOperationPostgresIntegrationTest.java | 530 +++++-- ...icyPublicationPostgresIntegrationTest.java | 6 +- ...electorSchemaMigrationIntegrationTest.java | 10 +- ...ionAssetExportSnapshotIntegrationTest.java | 156 +- ...aunchDescriptorServiceIntegrationTest.java | 10 + ...emptServiceTransactionIntegrationTest.java | 22 +- .../GameDesignReviewedBaseEvidenceTest.java | 29 +- .../publication/CommandSourceTest.java | 34 +- ...DesignPublicationOperationHistoryTest.java | 68 + .../publication/RealmPolicySourceTest.java | 25 + .../PublishedRealmPolicyEvidenceFixture.java | 7 +- .../logging-admin-service/build.gradle.kts | 1 + .../client/GameSessionClient.java | 11 + ...artSessionOperatorAuthorizationClient.java | 40 +- ...ionOperatorAuthorizationConfiguration.java | 5 +- .../StartSessionAuthorizationCoordinator.java | 654 +++++++- .../client/GameSessionClientTest.java | 49 +- ...onOperatorAuthorizationClientMtlsTest.java | 1034 +++++++++++++ ...essionOperatorAuthorizationClientTest.java | 74 +- ...rtSessionAuthorizationCoordinatorTest.java | 604 ++++++-- 75 files changed, 13419 insertions(+), 490 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1004__publication_operation_inventory_v2.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1005__gameplay_rule_source.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1006__draft_application_lifecycle_interlock.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1008__template_config_source_history.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1009__selected_publication_game_logic_receipt.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1010__selected_template_world_source_association.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1011__selected_publication_control_plane_digest_schema.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1012__normalized_template_references_and_tenant_phase.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1013__selected_inventory_asset_export_candidate.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1014__start_session_launch_descriptor_association_binding.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1015__template_config_owner_source_inventory.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1016__entity_template_config_owner_source_inventory.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1017__closure_qualified_selected_publication_attestation.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1018__selected_inventory_closure_profile.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1019__selected_release_original_account_owner_schema.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1020__selected_full_semantic_owner_attestation.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1021__retained_original_start_session_actor_core_projection.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1022__restore_selected_release_original_account_owner_schema.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1023__selected_export_artifact_projection.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedAssetSourceOwnerSetup.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationHistoryTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 2acaf0ac1e..ce0e3f7057 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -8,6 +8,8 @@ Accepted This ADR is partially implemented. Logging & Admin has current operator-facing read, investigation, admission-pointer read/audit, and prepared-upgrade proof-read surfaces, but no forwarded owner mutation family is currently supported as an executable external route until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption exist. The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They have no external Gateway route, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target Logging & Admin-owned moderation policy-input/audit path remains gated pending Account authorization-reference issuance plus Logging & Admin receiving-service validation/redemption; it does not require domain-owner redemption. The live `EvaluateModerationPolicy` read remains available only to its internal enforcement owners. Versioned policy propagation and owner enforcement remain target-state work. +The original StartSession receiver retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. Current receiving proof and its controlled-input limits are recorded in the [coherent owner receiving tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). This source preparation supplies no genuine producer, activation or operational-region proof. + ## Decision Record - Decision date: 2026-07-19 diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 7e66da5da1..bb46173ece 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -69,6 +69,8 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status +The coherent selected-publication receiver installs immutable source inventories, selected owner attestations and mandatory fresh-v2 operation/capture guards through V1023, then asset-bound reviewed-base v2 guards in V1024. Current Java callers supply complete v2 operation evidence and the ordinary asset owner participates in synchronized source and export projection. Original v1 operation/review bytes remain readable history without fresh write authority. This adds no registered publication ingress or activation authority. The canonical retention and fresh-operation rule is in [Version Control](./version-control.md#selected-publication-storage-and-retained-operations), with physical owner proof, controlled-input limits and current qualification in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). + The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 3bbb1e9832..c8854e4422 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,7 +6,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without frozen snapshot references may still be updated. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without frozen snapshot references may still be updated. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method fails closed because it carries no reviewed commit authority; the ordinary source-owner path and synchronized projection have controlled-input local PostgreSQL proof, while registered production authoring remains unavailable; exports use only the version's mapped set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. - **Current upload admission gap:** `GameAssetServiceImpl` now returns a structured owner-proof refusal before accessing `MultipartFile` or the repository because Account commit-bound authority is not wired. This deny-only containment does not implement the Account gate or make the Gateway-exposed route readiness-approved; it does not delete or rewrite previously accepted `game_assets` rows. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. - **Hosted-content gate gap:** Current publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route forwards `/api/design/assets` (after `StripPrefix=2`) to `POST /assets`, where the service refuses before file access or persistence. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable per-version source snapshot and export candidate preserve the selected rows and exact content-addressed object-key/digest evidence; the object writer verifies exact readback. Published repair independently reads the candidate and matches its manifest, artifact digests, and object keys to the release attestation before any object write. This does not implement the target global publication/purge fence or private candidate isolation; source identity and payload fields are database-protected while frozen snapshots reference them, and physical object-store proof remains unavailable. @@ -27,6 +27,12 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b Logical world and entity templates (regions, rooms, items, NPCs, loot tables, scripts, etc.) remain stored in PostgreSQL schemas owned by the corresponding domain services and are not persisted as blobs in the asset store. The asset store is strictly for binary design assets plus version-scoped manifests exported by the Game Design Service. +### Ordinary Asset Source Ownership + +A fresh full-Draft insertion establishes ordinary asset genesis in the same owner transaction as policy and command genesis, bound to the original Version insertion witness. Typed `ASSET_REFERENCE` revisions use the existing reviewed commit and coordinator application slot. Each declared source family contributes its exact application result and affected epoch to one complete Game Design owner outcome. Only the synchronized commit fence permits a source snapshot and its `version_asset` projection; direct mapping association is not an authority path. + +A new export snapshot requires the exact synchronized ordinary source snapshot, including an explicitly owner-founded empty set. Its items bind the source row, usage key, content type, byte size and actual-byte digest. Already retained V37 export snapshots remain read-only with their original bytes and metadata; absence of source history cannot be interpreted as empty or backfilled. The fresh reviewed-base and retained-evidence boundary is owned by [Version Control](version-control.md#selected-publication-storage-and-retained-operations). + Derived runtime-consumed artifacts produced by domain services follow the same writer rule: - Domain services may own the semantics and generation of derived artifacts such as navmesh/path graph bundles. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 8074e3693e..38a70e598b 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -8,7 +8,7 @@ Game Design is the canonical authored-history, publication-coordination, release The owner-local foundation stores canonical Version identity derived from the exact persisted Game row and canonical release identity with an owner-generated opaque reference. Retained Versions and bundles keep their original all-null canonical identity; new canonical inserts cannot mint identity for a retained unbound Version. Bundle writes are immutable, and demo restart reads and reuses the existing bundle. The additive asset-mapping and export-snapshot schemas do not activate asset publication; the complete source-bound fixture successor supplies its own claimed registration, receipt, and runtime handler boundary. State-changing `CompareAndSetVersionState` requests fail closed after tenant/version and expected-epoch checks, preserving same-state no-op; legal transition and database CAS proof remain unavailable. -The authenticated source-bound v1 `ResolveLaunchDescriptor` path and exact `GetLaunchDescriptor` readback are live; numeric-only tenant/template/version fallback does not authorize launch. Candidate validation and physical execution status are recorded in the [run-owned fixture repair tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). The v1 release read projection carries canonical version identity, an opaque release reference, manifest-schema metadata, and artifact-digest fields where present. Its current proto/mapper omit `tenantId`, so remote consumers cannot exact-compare the requested tenant/version pair (see [API contracts](api-contracts.md#implementation-status)); the fixture owner-local seed projection retains its separately verified tenant identity. Producer population and retained-row backfill remain unproved. First-slice Version state-changing requests fail closed after tenant/version and expected-epoch checks, with a same-state no-op preserved. Production asset upload and fresh/PENDING full-version publication remain fail-closed. Version-mapped export snapshots and candidates, artifact publication state, exact-byte repair, and complete launch-binding readback are present in this private source, but normal Draft asset association has no production caller and these mechanics do not establish production publication or physical database, object-store, or Temporal proof. The three production release-bundle, version-state, and artifact-state read RPCs retain exact-peer default denial before owner reads, as specified below. External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). +The authenticated source-bound v1 `ResolveLaunchDescriptor` path and exact `GetLaunchDescriptor` readback are live; numeric-only tenant/template/version fallback does not authorize launch. Candidate validation and physical execution status are recorded in the [run-owned fixture repair tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). The v1 release read projection carries canonical version identity, an opaque release reference, manifest-schema metadata, and artifact-digest fields where present. Its current proto/mapper omit `tenantId`, so remote consumers cannot exact-compare the requested tenant/version pair (see [API contracts](api-contracts.md#implementation-status)); the fixture owner-local seed projection retains its separately verified tenant identity. Producer population and retained-row backfill remain unproved. First-slice Version state-changing requests fail closed after tenant/version and expected-epoch checks, with a same-state no-op preserved. Production asset upload and fresh/PENDING full-version publication remain fail-closed. Version-mapped export snapshots and candidates, artifact publication state, exact-byte repair, and complete launch-binding readback are present in this private source, but registered ordinary Draft asset authoring has no production caller. The reviewed ordinary source owner and synchronized projection have bounded controlled-input PostgreSQL proof in the [receiving tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite); these mechanics do not establish production publication, physical object-store or Temporal proof. The three production release-bundle, version-state, and artifact-state read RPCs retain exact-peer default denial before owner reads, as specified below. External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). `GetCompleteLaunchBinding` retains its exact same-namespace candidate peer check for Game Session, World Management, and Entity Management, then defaults to `PERMISSION_DENIED` before the owner read. Production access remains unavailable pending genuine operation-specific tenant/scope authority; this RPC gate does not disable the owner-local service or direct fixture proof. @@ -22,6 +22,12 @@ Current cross-seam security status is also blocked: Account's runtime membership 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. +## Selected Publication Storage and Retained Operations + +Game Design retains the exact selected publication operation, source captures and owner attestations as immutable evidence. Fresh `game-design-publication-operation/v2` includes the original Account authorization, recipient-qualified World selector and complete public World inventory with its exact digest. Storage checks the operation framing, child correlation, selected commit and supported inventory profile before accepting a new reservation, source capture or derived publication evidence. A closure-qualified inventory must retain its explicit inbound declaration and paired graph/digest schema; a digest alone cannot replace those inputs. + +Original retained three-frame v1 bytes remain readable with their original row and request checksums. They do not establish inventory completeness and cannot authorize a new operation reservation, capture or terminal seal after the v2 storage guards apply. Forward migrations do not rewrite those bytes or fabricate source history. Forward migrations also preserve original `game-design-reviewed-draft-base/v1` rows and their exact bytes. Fresh reviewed-base v2 evidence binds the original policy, command and ordinary asset genesis, or the exact synchronized snapshots and complete owner vector for an authored base. An old review without ordinary asset lineage remains readable and cannot authorize a fresh source write. The database independently reconstructs fresh review bytes from the retained owner records before accepting the claim. Source-family inventories, exact Game Logic and World associations, normalized template references, original Account owner schema and candidate projection remain separate retained owner facts; installing their tables and guards does not produce those facts or enable publication. + ## Approach - Each asset revision already stores author and timestamp metadata. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 39101efd31..0e48888d45 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -12,6 +12,8 @@ Implementation status: the claim-evidence receiver and Account read client exist When enabled, the Spring composition requires the configured canonical workload namespace and readable file-backed client mTLS inputs, initializes the typed Account client through the managed bean lifecycle, and connects it to the existing durable reservation service. The configuration supplies no reservation or authority source and exposes no external route. Its context test uses a controlled channel factory and test-only placeholder TLS files; it does not prove physical mTLS, production service startup, remote Account availability, or execution through Game Session launch selection and World activation. The target authorization and owner-forwarding rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). +Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple with its exact reserved operation and validated response, persists those unchanged Account bytes, and independently reads back the same durable authorization before advancing the one-time owner handoff. Exact retries may observe secret-free durable state but never return another transient reference or dispatch again. Ambiguous Account calls, local completion, readback, or owner-pending transitions remain pending with no automatic replacement issuance or rearming. ISSUE, RECOVER, and owner forwarding require no ambient SQL transaction or synchronization. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns original tuple and capture-reference binding; this local receiving boundary does not activate operator ingress or replace Account current-authority and expiry decisions. + ## Account Audit Ingress and Receipt The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). @@ -113,8 +115,6 @@ The implementation gap is fail-closed: the HTTP controller and Gateway route are The source-level `StartSessionAuthorizationCoordinator` now offers separate `issueHumanAndDispatch` and `recoverAndDispatch` methods that compose its existing authorization/recovery flow with `GameSessionClient`. They call the owner once only when that invocation wins the durable `OWNER_EXECUTION_PENDING` transition; exact/in-progress and recovery-unavailable results do not dispatch, and ambiguous owner outcomes propagate without automatic retry or rearming. The existing `issueHuman` and `recover` methods remain prepare-only. The typed `GameSessionClient` call sends the transient post-authorization tuple/reference and validates Game Session's secret-free durable attempt/progress echo; it requires readable file-backed workload mTLS and pins both request and response to the exact same-namespace Game Session SPIFFE URI derived from the tuple. Ping and stop keep their existing client behavior. These methods are not wired to a routable Logging & Admin StartSession ingress. Mocked tests do not establish physical mTLS, production ingress, prepared launch selection, or instance activation. -The Account client accepts the new StartSession response only after comparing its complete returned owner tuple with the exact reservation and response evidence. The coordinator retains and hands off the Account-returned tuple bytes through the existing completion/recovery path, under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). Missing or substituted owner evidence fails closed before durable completion or owner dispatch; this does not activate a routable ingress. - **Target ADR 0047/0048 owner-forwarding path:** [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) owns the Logging & Admin ingress and Account-reference issuance boundary; [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) owns the phase-qualified execution, redemption, and reconciliation contract. Supported executable operator mutations use Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) issuance RPC after Logging & Admin authenticates the current `control-ui` actor and records durable intent. Logging & Admin forwards the opaque bounded reference and unchanged request/generation binding; the authoritative receiving owner recomputes the canonical digest and is the only service that calls Account's `RedeemOperatorAuthorization` RPC. Unattended automation uses Account's `IssueAutomationOperatorAuthorizationReference` with `exact_mtls_workload_plus_versioned_automation_policy`, bound to the exact Logging and Admin workload mTLS identity and current `automation_policy_id`/`automation_policy_version`; the currently supported automation branch is tenant-scoped only and carries the exact target `tenant_generation` through issuance, forwarding, redemption, and owner commit. It carries no human identity, end-user token, or `privileged_control` authority. For each owner contract, predicate evidence comes exclusively from Account's redemption response; any copy forwarded by Logging & Admin is unchanged audit/context evidence, not authority. The local `/moderation/actions` policy-input/audit mutation is a separate receiving-service path: after its gate exists, Logging & Admin redeems its one Account reference exactly once for local persistence and never forwards or reuses that reference. Any future moderation owner-enforcement command uses a separately issued command-bound reference redeemed exactly once by the receiving owner. The moderation route is currently gated/unavailable; it hard fails closed without dispatch or persistence and performs no target fixed-category policy/audit persistence or forwarding. `EvaluateModerationPolicy` is a live read and carries no mutation authorization reference. For non-moderation action families, the request identity is the exact `controlPlaneRequestId` plus digest pair. Moderation and appeal transports instead use dedicated `policyIntentRequestId`, `ownerEnforcementRequestId`, and stable appeal-submission request identities end-to-end; `controlPlaneRequestId` remains a separate correlation-only field and must not carry, replace, alias, or serve as any of those mutation identities. The dedicated identities are never shared or reused. Logging & Admin never becomes a second authorization authority. Current feature-flag and tick forwarding paths, plus internal admission control-plane implementations, are not evidence that this ADR 0048 target contract is complete. For every forwarded owner mutation, excluding the separate local `/moderation/actions` policy-input/audit path, the authoritative owner calls Account's `RedeemOperatorAuthorization` with the separately issued opaque reference and its independently derived request binding. Authorization predicates and generation authority come exclusively from that Account response. Any predicate, generation, checkpoint, or assurance copies forwarded by Logging & Admin are unchanged audit/context evidence only; the owner must not authorize or mutate from those copies, and they are excluded from the canonical `mutationDigest/v1`, which covers the normalized action request rather than ingress assertions. The local moderation route is gated/unavailable; it hard fails closed without dispatch or persistence and does not persist target fixed-category policy/audit evidence, redeem, forward, or enforce. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 849b7429d8..4d5c8ed790 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -246,3 +246,9 @@ Entry format: - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. - Current status: the required proof using packaged service artifacts passes both transports with the isolated configuration and pinned public images. This client failure establishes neither an application regression nor a cause for the earlier Testcontainers endpoint refusals. + +- `2026-10-14`: Qualify a receiving boundary from all current postimages and actual owner dependencies + - Context: the Document receiving reconstruction initially inventoried only the published delta and untracked additions, omitting modified tracked source. Treating additive storage guards as passive also missed the fresh-v2 callers and ordinary asset source owner required by current positive publication tests. + - Observation: the complete preserved delta had 84 paths, with a coherent 63-path Game Design boundary after inherited Account/process and separate Logging paths were accounted for. Current-owner proof required actual asset genesis, reviewed evidence and synchronized projection; decoding retained v1 history could not substitute for those callers. PostgreSQL's unnamed constraint identity also differed from jOOQ's H2 metadata emulation. + - Expected pattern: inventory committed, modified tracked and untracked postimages together, then reconcile actual imports and owner invariants on the selected parent. Keep retained-byte proof separate from current positive owner proof. Use targeted jOOQ ignore markers only for procedural or constraint blocks that do not change generated columns, with independent PostgreSQL upgrade and current-owner proof. + - Current status: the complete 63-path Game Design receiver on the preparation parent passes its canonical gate, including all 127 physical PostgreSQL cases without skips. This does not establish genuine cross-service producer authority or packaged runtime proof. 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 0f619ebb15..03a8231a3f 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,18 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. + +### Coherent owner receiving prerequisite + +The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. + +The complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passes formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executes 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executes all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history has 62 entries; upgrade and fresh histories have 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases keep their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verifies their unchanged inputs as up-to-date rather than relabeling them fresh. + +Final parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changes only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`; all Account, Common, Game Design, Logging and migration inputs are byte-identical. The parent proofs separately cover Entity's 237 unit and 26 physical PostgreSQL cases and Account's 18 physical PostgreSQL cases without failures, errors or skips. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. + +External Account/World inputs in the storage and source fixtures remain explicitly controlled. Current Java callers issue complete fresh-v2 operations; the decoder preserves original three-frame v1 bytes as read-only history without inventory authority. Installing source tables and proving owner-local behavior does not register a genuine producer, establish rebuilt runtime proof for the receiver, authorize activation or complete any Gameplay handoff. All four genuine handoffs, full publication, protected activation, Entity placement and operational-region delivery remain open; broader Unit 1B stays paused. The owning storage and reviewed-base contract is [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). + 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. diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index ceda8f3cfc..1261876954 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -29,6 +29,7 @@ dependencies { compileOnly(libs.spotbugs.annotations) testImplementation(libs.grpc.spring.boot.starter) testImplementation(libs.spring.boot.starter.test) + testImplementation(testFixtures(project(":common-test-support"))) testFixturesApi(platform(libs.spring.boot.dependencies)) testFixturesApi("tools.jackson.core:jackson-databind") } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java new file mode 100644 index 0000000000..65e60aaf3d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.gamedesign; + +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; + +/** Ordinary selected source only; no total inventory or template/branding completeness claim. */ +public record AssetSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public AssetSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact ordinary asset source epoch and genesis required"); + items = List.copyOf(items); + new AssetSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Ordinary asset items must be in canonical key order"); + } + + public record Item( + AssetSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact ordinary asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-ordinary-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "items", + items.stream().map(Item::object).toList())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static AssetSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "items"); + if (!"game-design-ordinary-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported ordinary asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!AssetSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family")) + || !AssetSource.ROLE.equals(CommandSource.requiredStoredText(node, "role"))) + throw new IllegalArgumentException("Unsupported ordinary source family or role"); + var reference = + new AssetSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + AssetSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new AssetSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical ordinary asset snapshot"); + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java new file mode 100644 index 0000000000..cdf1d221e6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed read evidence for one exact durable synchronized Game Design Draft visibility fence. */ +public final class DraftSynchronizedVisibilityEvidence { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = new ObjectMapper(); + + /** Complete Game Design target selector, plus a distinct caller-owned read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + DraftCommitBinding.TargetProof target) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported synchronized visibility schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("A canonical target namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(target, "target"); + } + } + + /** Exact immutable fence tuple as retained by the Game Design coordinator. */ + public record Fence( + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) { + public Fence { + requireNonNil(requestId, "fence requestId"); + requireNonNil(commitId, "fence commitId"); + requireDigest(inputDigest, "fence inputDigest"); + Objects.requireNonNull(resultVectorJson, "resultVectorJson"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } + + /** One exact APPLIED owner result decoded from the coordinator's immutable result vector. */ + public static final class AppliedOwnerResult { + private final Owner owner; + private final UUID commitId; + private final String bindingDigest; + private final String resultIdentity; + private final byte[] resultBytes; + private final List appliedEpochs; + + private AppliedOwnerResult( + Owner owner, + UUID commitId, + String bindingDigest, + String resultIdentity, + byte[] resultBytes, + List appliedEpochs) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.commitId = Objects.requireNonNull(commitId, "commitId"); + this.bindingDigest = Objects.requireNonNull(bindingDigest, "bindingDigest"); + this.resultIdentity = Objects.requireNonNull(resultIdentity, "resultIdentity"); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + this.appliedEpochs = List.copyOf(appliedEpochs); + } + + public Owner owner() { + return owner; + } + + public UUID commitId() { + return commitId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public String resultIdentity() { + return resultIdentity; + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public List appliedEpochs() { + return appliedEpochs; + } + } + + public record AppliedEpoch( + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch, + String resultingEpoch) { + public AppliedEpoch { + Objects.requireNonNull(aggregateType, "aggregateType"); + Objects.requireNonNull(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + requireCounter(expectedEpoch, "expectedEpoch"); + requireCounter(resultingEpoch, "resultingEpoch"); + } + } + + private final Request request; + private final DraftCommitBinding binding; + private final String workflowState; + private final Fence fence; + private final List appliedOwnerResults; + + public DraftSynchronizedVisibilityEvidence( + Request request, DraftCommitBinding binding, String workflowState, Fence fence) { + this.request = Objects.requireNonNull(request, "request"); + this.binding = Objects.requireNonNull(binding, "binding"); + this.workflowState = Objects.requireNonNull(workflowState, "workflowState"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.appliedOwnerResults = validateAndReadOwnerResults(); + } + + public Request request() { + return request; + } + + public DraftCommitBinding binding() { + return binding; + } + + public String workflowState() { + return workflowState; + } + + public Fence fence() { + return fence; + } + + public List appliedOwnerResults() { + return List.copyOf(appliedOwnerResults); + } + + public AppliedOwnerResult appliedOwnerResult(Owner owner) { + Objects.requireNonNull(owner, "owner"); + return appliedOwnerResults.stream() + .filter(result -> result.owner() == owner) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Owner is not in the applied fence")); + } + + /** Revalidates every redundant carrier before this evidence is used as a selector. */ + public void requireValid() { + validateAndReadOwnerResults(); + } + + private List validateAndReadOwnerResults() { + if (!binding.target().equals(request.target()) + || !binding.requiredOwners().contains(Owner.WORLD_MANAGEMENT) + || request.readRequestId().equals(binding.requestId()) + || request.readRequestId().equals(binding.commitId())) { + throw new IllegalArgumentException( + "Synchronized visibility request and complete Draft target differ"); + } + if (!"SYNCHRONIZED".equals(workflowState) + || !fence.requestId().equals(binding.requestId()) + || !fence.commitId().equals(binding.commitId()) + || !fence.inputDigest().equals(binding.digest())) { + throw new IllegalArgumentException( + "Draft visibility fence is not bound to this synchronized full input"); + } + + byte[] supplied = fence.resultVectorJson().getBytes(StandardCharsets.UTF_8); + byte[] canonical; + JsonNode vector; + try { + canonical = Rfc8785CanonicalJson.canonicalizeUtf8(fence.resultVectorJson()); + vector = JSON.readTree(fence.resultVectorJson()); + } catch (IOException | RuntimeException exception) { + throw new IllegalArgumentException( + "Draft result vector is not valid canonical JSON", exception); + } + if (!java.util.Arrays.equals(supplied, canonical)) { + throw new IllegalArgumentException("Draft result vector is not exact canonical JSON"); + } + if (vector == null || !vector.isArray() || vector.size() != binding.requiredOwners().size()) { + throw new IllegalArgumentException("Draft result vector is incomplete"); + } + + List results = new ArrayList<>(); + Set seen = new HashSet<>(); + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + requireFields( + item, + Set.of( + "owner", + "status", + "commitId", + "bindingDigest", + "resultIdentity", + "resultBytesBase64", + "appliedEpochs")); + Owner owner = enumText(item, "owner", Owner.class); + if (owner != binding.requiredOwners().get(index) || !seen.add(owner)) { + throw new IllegalArgumentException("Draft owner result order/set differs from binding"); + } + if (!"APPLIED".equals(text(item, "status"))) { + throw new IllegalArgumentException("Only terminal APPLIED owner results are visible"); + } + UUID commitId = parseCanonicalUuid(text(item, "commitId"), "commitId"); + String bindingDigest = text(item, "bindingDigest"); + requireDigest(bindingDigest, "owner bindingDigest"); + String resultIdentity = text(item, "resultIdentity"); + if (resultIdentity.isBlank() || !resultIdentity.equals(resultIdentity.trim())) { + throw new IllegalArgumentException("Owner result identity must be exact nonblank text"); + } + String bytesBase64 = text(item, "resultBytesBase64"); + byte[] resultBytes; + try { + resultBytes = Base64.getDecoder().decode(bytesBase64); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Owner result bytes must be canonical Base64", exception); + } + if (!Base64.getEncoder().encodeToString(resultBytes).equals(bytesBase64)) { + throw new IllegalArgumentException("Owner result bytes must be canonical Base64"); + } + if (!binding.commitId().equals(commitId) || !binding.digest().equals(bindingDigest)) { + throw new IllegalArgumentException("Owner result is bound to different Draft input"); + } + List epochs = parseEpochs(item.get("appliedEpochs"), binding, owner); + results.add( + new AppliedOwnerResult( + owner, commitId, bindingDigest, resultIdentity, resultBytes, epochs)); + } + return List.copyOf(results); + } + + private static List parseEpochs( + JsonNode vector, DraftCommitBinding binding, Owner owner) { + List expected = binding.affectedUnits(owner); + if (vector == null || !vector.isArray() || vector.size() != expected.size()) { + throw new IllegalArgumentException("Applied owner epoch vector is incomplete"); + } + List epochs = new ArrayList<>(); + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + requireFields( + item, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + AppliedEpoch epoch = + new AppliedEpoch( + text(item, "aggregateType"), + text(item, "aggregateId"), + text(item, "scopeType"), + text(item, "scopeId"), + text(item, "expectedEpoch"), + text(item, "resultingEpoch")); + AffectedUnit unit = expected.get(index); + if (!unit.aggregateType().equals(epoch.aggregateType()) + || !unit.aggregateId().equals(epoch.aggregateId()) + || !unit.scopeType().equals(epoch.scopeType()) + || !unit.scopeId().equals(epoch.scopeId()) + || !unit.expectedEpoch().equals(epoch.expectedEpoch()) + || new BigInteger(epoch.resultingEpoch()).compareTo(new BigInteger(epoch.expectedEpoch())) + <= 0) { + throw new IllegalArgumentException( + "Applied owner tuple differs from the complete bound epoch declaration"); + } + epochs.add(epoch); + } + return List.copyOf(epochs); + } + + private static void requireFields(JsonNode node, Set fields) { + if (node == null + || !node.isObject() + || node.size() != fields.size() + || node.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Draft owner result contains missing or unknown fields"); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Draft owner result text field is missing: " + field); + } + return value.textValue(); + } + + private static > T enumText(JsonNode node, String field, Class type) { + try { + return Enum.valueOf(type, text(node, field)); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Draft owner result enum is unsupported: " + field, exception); + } + } + + private static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical SHA-256 text"); + } + } + + private static void requireCounter(String value, String label) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java index 0d664c9a04..a56ca94c38 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -7,17 +7,67 @@ import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** Original closed publication input; byte integrity never authenticates its producer. */ -public record GameDesignPublicationOperationBinding( - AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { - public static final String SCHEMA = "game-design-publication-operation/v1"; +public final class GameDesignPublicationOperationBinding { + public static final String SCHEMA = "game-design-publication-operation/v2"; + public static final int MAX_OPERATION_BYTES = 4 * 1024 * 1024; - public GameDesignPublicationOperationBinding { + private static final String HISTORICAL_SCHEMA = "game-design-publication-operation/v1"; + + private enum Profile { + HISTORICAL_V1, + COMPLETE_V2 + } + + private final AccountPublicationAuthorizationBinding account; + private final WorldPublishedStartLocationEvidence world; + private final WorldSelectedPublicationArtifactInventoryEvidence inventory; + private final Profile profile; + + public GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory) { + this(account, world, Objects.requireNonNull(inventory, "inventory"), Profile.COMPLETE_V2); + } + + private GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory, + Profile profile) { account = AccountPublicationAuthorizationBinding.fromStored( Objects.requireNonNull(account).canonicalBytes()); world = WorldPublishedStartLocationEvidence.fromStored( Objects.requireNonNull(world).canonicalBytes()); + requireAccountWorldCorrelation(account, world); + this.account = account; + this.world = world; + this.profile = profile; + if (profile == Profile.HISTORICAL_V1) { + this.inventory = null; + return; + } + Objects.requireNonNull(inventory, "inventory"); + inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, inventory.canonicalBytes(), inventory.digest()); + this.inventory = inventory; + long size = + 5L * Integer.BYTES + + SCHEMA.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + + account.canonicalBytes().length + + world.canonicalBytes().length + + inventory.canonicalBytes().length + + inventory.digest().length(); + if (size > MAX_OPERATION_BYTES) + throw new IllegalArgumentException("Publication operation exceeds 4 MiB"); + } + + /** Historical correlation only; neither authentication nor complete operation authority. */ + public static void requireAccountWorldCorrelation( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { var selection = account.input().selection(); var intent = selection.intent(); var freeze = world.request(); @@ -43,21 +93,69 @@ public record GameDesignPublicationOperationBinding( } } + public AccountPublicationAuthorizationBinding account() { + return account; + } + + public WorldPublishedStartLocationEvidence world() { + return world; + } + + /** Retained v1 history cannot supply complete inventory or fresh publication authority. */ + public WorldSelectedPublicationArtifactInventoryEvidence inventory() { + if (profile == Profile.HISTORICAL_V1) + throw new IllegalStateException("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + return inventory; + } + public byte[] canonicalBytes() { var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame( + out, profile == Profile.HISTORICAL_V1 ? HISTORICAL_SCHEMA : SCHEMA); DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + if (profile == Profile.COMPLETE_V2) { + DraftAuthorizationFenceBinding.frame(out, inventory.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inventory.digest()); + } return out.toByteArray(); } + @Override + public boolean equals(Object other) { + return other instanceof GameDesignPublicationOperationBinding binding + && Arrays.equals(canonicalBytes(), binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + public static GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0) + throw new IllegalArgumentException("Original publication operation required"); var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); - reader.expect(SCHEMA); - var operation = - new GameDesignPublicationOperationBinding( - AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), - WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + String schema = reader.text(); + boolean historical = HISTORICAL_SCHEMA.equals(schema); + if (!historical && (!SCHEMA.equals(schema) || bytes.length > MAX_OPERATION_BYTES)) + throw new IllegalArgumentException("Complete bounded v2 publication operation required"); + var account = AccountPublicationAuthorizationBinding.fromStored(reader.bytes()); + var world = WorldPublishedStartLocationEvidence.fromStored(reader.bytes()); + GameDesignPublicationOperationBinding operation; + if (historical) { + operation = + new GameDesignPublicationOperationBinding(account, world, null, Profile.HISTORICAL_V1); + } else { + var inventoryBytes = reader.bytes(); + String digest = new String(reader.bytes(), java.nio.charset.StandardCharsets.US_ASCII); + operation = + new GameDesignPublicationOperationBinding( + account, + world, + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, inventoryBytes, digest)); + } reader.requireEnd(); if (!Arrays.equals(bytes, operation.canonicalBytes())) { throw new IllegalArgumentException("Noncanonical publication operation"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java new file mode 100644 index 0000000000..5435410efa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact selected-publication freeze request and its committed World acknowledgement. */ +public final class WorldSelectedDraftPublicationFreezeEvidence { + private final Request request; + private final Acknowledgement acknowledgement; + + WorldSelectedDraftPublicationFreezeEvidence(Request request, Acknowledgement acknowledgement) { + this.request = Objects.requireNonNull(request, "request"); + this.acknowledgement = Objects.requireNonNull(acknowledgement, "acknowledgement"); + if (!request.equals(acknowledgement.request())) { + throw new IllegalArgumentException("World freeze acknowledgement changed its exact request"); + } + } + + public Request request() { + return request; + } + + public Acknowledgement acknowledgement() { + return acknowledgement; + } + + @Override + public boolean equals(Object other) { + return other instanceof WorldSelectedDraftPublicationFreezeEvidence that + && request.equals(that.request) + && acknowledgement.equals(that.acknowledgement); + } + + @Override + public int hashCode() { + return Objects.hash(request, acknowledgement); + } + + /** Complete exact request from Game Design; its Account bytes are correlation, not authority. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publicationRequestId, + long expectedVersionStateEpoch, + String requestDigest, + byte[] accountPublicationAuthorizationBinding) { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_ACCOUNT_BINDING_BYTES = 1_048_576; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World selected-freeze schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + if (expectedVersionStateEpoch <= 0L) { + throw new IllegalArgumentException("Expected Version state epoch must be positive"); + } + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException( + "Request digest must be 64 lowercase hexadecimal digits"); + } + if (accountPublicationAuthorizationBinding == null + || accountPublicationAuthorizationBinding.length == 0 + || accountPublicationAuthorizationBinding.length > MAX_ACCOUNT_BINDING_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication binding is required"); + } + accountPublicationAuthorizationBinding = accountPublicationAuthorizationBinding.clone(); + AccountPublicationAuthorizationBinding account = + AccountPublicationAuthorizationBinding.fromStored(accountPublicationAuthorizationBinding); + if (!Arrays.equals(accountPublicationAuthorizationBinding, account.canonicalBytes())) { + throw new IllegalArgumentException("Account publication binding is not canonical"); + } + var selection = account.input().selection(); + if (!account.tenantId().equals(canonicalTenantId) + || !selection.intent().canonicalVersionId().equals(canonicalVersionId) + || !selection.intent().publishRequestId().equals(publicationRequestId) + || !selection + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(expectedVersionStateEpoch)) + || !selection.digest().equals("sha256:" + requestDigest)) { + throw new IllegalArgumentException( + "World freeze request differs from the exact Account-bound immutable selection"); + } + // Also validates the canonical full-version request identity and stable workflow syntax. + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + publicationRequestId); + } + + public static Request create( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publicationRequestId, + long expectedVersionStateEpoch, + String requestDigest, + AccountPublicationAuthorizationBinding accountBinding) { + Objects.requireNonNull(accountBinding, "accountBinding"); + return new Request( + SCHEMA_VERSION, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + publicationRequestId, + expectedVersionStateEpoch, + requestDigest, + accountBinding.canonicalBytes()); + } + + @Override + public byte[] accountPublicationAuthorizationBinding() { + return accountPublicationAuthorizationBinding.clone(); + } + + /** Reconstructs the complete canonical original Account publication order. */ + public AccountPublicationAuthorizationBinding accountBinding() { + AccountPublicationAuthorizationBinding binding = + AccountPublicationAuthorizationBinding.fromStored(accountPublicationAuthorizationBinding); + if (!Arrays.equals(accountPublicationAuthorizationBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Account publication binding is not canonical"); + } + return binding; + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && canonicalTenantId.equals(that.canonicalTenantId) + && canonicalVersionId.equals(that.canonicalVersionId) + && publicationRequestId.equals(that.publicationRequestId) + && expectedVersionStateEpoch == that.expectedVersionStateEpoch + && requestDigest.equals(that.requestDigest) + && Arrays.equals( + accountPublicationAuthorizationBinding, that.accountPublicationAuthorizationBinding); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + schemaVersion, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + publicationRequestId, + expectedVersionStateEpoch, + requestDigest) + + Arrays.hashCode(accountPublicationAuthorizationBinding); + } + + private static void requireUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + } + + /** Acknowledgement of the committed FROZEN event only, never a terminal or admission result. */ + public record Acknowledgement( + Request request, + UUID intakeRequestId, + long versionStateEpoch, + UUID publicationFence, + OwnerFreezePhase ownerFreezePhase, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + public Acknowledgement { + Objects.requireNonNull(request, "request"); + if (intakeRequestId == null || NIL_UUID.equals(intakeRequestId)) { + throw new IllegalArgumentException( + "World intake correlation must be a non-nil owner-produced UUID"); + } + if (versionStateEpoch <= 0L || versionStateEpoch != request.expectedVersionStateEpoch()) { + throw new IllegalArgumentException( + "World-observed Version state epoch differs from the exact request expectation"); + } + if (publicationFence == null || NIL_UUID.equals(publicationFence)) { + throw new IllegalArgumentException("World publication fence must be a non-nil UUID"); + } + if (ownerFreezePhase != OwnerFreezePhase.FROZEN) { + throw new IllegalArgumentException("World freeze acknowledgement must be FROZEN"); + } + UUID selectedCommitId = + request.accountBinding().input().selection().selectedCommit().commitId(); + if (!selectedCommitId.toString().equals(appliedCommitId)) { + throw new IllegalArgumentException( + "World applied commit differs from the exact selected Draft commit"); + } + if (contentDigest == null || !CONTENT_DIGEST.matcher(contentDigest).matches()) { + throw new IllegalArgumentException( + "World content digest must be canonical lowercase SHA-256"); + } + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("World digest schema version must be positive"); + } + } + + public String tenantId() { + return request.canonicalTenantId().toString(); + } + + public String versionId() { + return request.canonicalVersionId().toString(); + } + + public String publicationRequestId() { + return request.publicationRequestId(); + } + + public String requestDigest() { + return request.requestDigest(); + } + + public long versionStateEpoch() { + return versionStateEpoch; + } + } + + public enum OwnerFreezePhase { + FROZEN + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java new file mode 100644 index 0000000000..b682cb12c5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java @@ -0,0 +1,781 @@ +package net.firedevops.firemud.common.publication; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.IOException; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Typed World public inventory bound to one exact retained selected-publication freeze. + * + *

This value alone does not authenticate its producer; the authenticated mTLS caller and + * verified World server identity path supply that boundary. + */ +public final class WorldSelectedPublicationArtifactInventoryEvidence { + public static final String SCHEMA = "world-selected-publication-artifact-inventory/v1"; + public static final String SOURCE_MODEL = "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"; + public static final int SCHEMA_VERSION = 1; + public static final String INBOUND_CLOSURE_SCHEMA = + "world-selected-publication-artifact-inventory/v2"; + public static final String INBOUND_CLOSURE_SOURCE_MODEL = + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1"; + public static final int INBOUND_CLOSURE_SCHEMA_VERSION = 2; + public static final int INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION = 3; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern HEX_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final List FAMILY_ORDER = + List.of( + "REGION", "ZONE", "ROOM", "ROOM_EXIT", "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); + private static final List INBOUND_SOURCE_FAMILY_ORDER = + List.of( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"); + private static final List REGION_FIELDS = + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + private static final List ZONE_FIELDS = List.of("id", "regionId", "name"); + private static final List ROOM_FIELDS = + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + private static final List ROOM_EXIT_FIELDS = + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"); + private static final List GENERATION_RULE_FIELDS = + List.of("id", "name", "scopeType", "scopeId", "value"); + private static final List SPAWN_BINDING_FIELDS = + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"); + private static final List ARTIFACT_DECISIONS = + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + private final PublicEvidence publicEvidence; + private final byte[] canonicalBytes; + private final String digest; + + @Override + public boolean equals(Object other) { + return other instanceof WorldSelectedPublicationArtifactInventoryEvidence evidence + && Arrays.equals(canonicalBytes, evidence.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private WorldSelectedPublicationArtifactInventoryEvidence( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) { + this.freezeEvidence = Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + this.publicEvidence = Objects.requireNonNull(publicEvidence, "publicEvidence"); + requireFreezeBinding(freezeEvidence, publicEvidence); + this.canonicalBytes = publicEvidence.canonicalBytes(); + this.digest = sha256(canonicalBytes); + } + + /** Creates evidence from World’s typed public projection and validates every public binding. */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromPublicEvidence( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) { + return new WorldSelectedPublicationArtifactInventoryEvidence(freezeEvidence, publicEvidence); + } + + /** + * Strictly parses canonical public evidence, validates its digest, then binds it to the freeze. + */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromCanonicalBytes( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + byte[] canonicalBytes, + String expectedDigest) { + Objects.requireNonNull(canonicalBytes, "canonicalBytes"); + requireDigest(expectedDigest, "public inventory digest"); + if (!sha256(canonicalBytes).equals(expectedDigest)) { + throw new IllegalArgumentException("World public inventory digest does not match its bytes"); + } + final PublicEvidence evidence; + try { + evidence = JSON.readValue(canonicalBytes, PublicEvidence.class); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World public inventory is not a closed typed value", invalid); + } + if (evidence == null || !Arrays.equals(canonicalBytes, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World public inventory is not canonical JSON"); + } + return new WorldSelectedPublicationArtifactInventoryEvidence(freezeEvidence, evidence); + } + + /** + * Reconstructs original freeze correlation from retained Account/selector evidence. This never + * authenticates a producer anew and cannot substitute for the first authenticated owner read. + */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromRetainedSelection( + AccountPublicationAuthorizationBinding account, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence world, + byte[] inventoryBytes, + String inventoryDigest) { + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation(account, world); + var selector = world.request(); + var request = + Request.create( + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.canonicalVersionId(), + selector.publicationRequestId(), + selector.versionStateEpoch(), + selector.requestDigest(), + account); + var acknowledgement = + new Acknowledgement( + request, + selector.intakeRequestId(), + selector.versionStateEpoch(), + selector.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + selector.appliedCommitId(), + selector.contentDigest(), + selector.digestSchemaVersion()); + var result = + fromCanonicalBytes( + new WorldSelectedDraftPublicationFreezeEvidence(request, acknowledgement), + inventoryBytes, + inventoryDigest); + var original = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + world.originalAccountBindingBytes()); + var receipt = + net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence.fromStored( + world.selectorReceiptBytes()); + final tools.jackson.databind.JsonNode applied; + try { + applied = JSON.readTree(world.appliedResultBytes()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Retained World APPLIED bytes are invalid", invalid); + } + byte[] operationBytes; + try { + operationBytes = + java.util.Base64.getDecoder().decode(applied.path("operationBytesBase64").textValue()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Retained World APPLIED operation is invalid", invalid); + } + var operation = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader( + operationBytes); + operation.expect("world-draft-terminal-operation/v1"); + String operationId = new String(operation.bytes(), java.nio.charset.StandardCharsets.UTF_8); + var application = result.publicEvidence().selectedApplication(); + if (!sha256(world.appliedResultBytes()).equals(application.appliedResultDigest()) + || !original.operationId().equals(application.applicationOperationId()) + || !application.applicationOperationId().toString().equals(operationId) + || !receipt.graphDigest().equals(result.publicEvidence().sourceModel().graphDigest()) + || !receipt.graphDigest().equals(applied.path("graphDigest").textValue())) { + throw new IllegalArgumentException( + "World inventory differs from exact selector APPLIED operation or graph"); + } + return result; + } + + public WorldSelectedDraftPublicationFreezeEvidence freezeEvidence() { + return freezeEvidence; + } + + public PublicEvidence publicEvidence() { + return publicEvidence; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static void requireFreezeBinding( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence evidence) { + Request request = freezeEvidence.request(); + Acknowledgement acknowledgement = freezeEvidence.acknowledgement(); + AccountPublicationAuthorizationBinding account = request.accountBinding(); + var selection = account.input().selection(); + var intent = selection.intent(); + var selectedCommit = selection.selectedCommit(); + var owner = evidence.ownerScope(); + var application = evidence.selectedApplication(); + var accountOrder = evidence.accountOrder(); + var freeze = evidence.freeze(); + var checkpoint = evidence.checkpoint(); + var sourceModel = evidence.sourceModel(); + String expectedWorkflow = + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity(); + + if (!owner.targetNamespace().equals(request.targetNamespace()) + || !owner.canonicalTenantId().equals(request.canonicalTenantId()) + || !owner.canonicalVersionId().equals(request.canonicalVersionId()) + || !owner.intakeRequestId().equals(acknowledgement.intakeRequestId()) + || !application.applicationRequestId().equals(selectedCommit.requestId()) + || !application.appliedCommitId().equals(selectedCommit.commitId().toString()) + || !application.bindingDigest().equals(selectedCommit.digest()) + || !accountOrder.operationId().equals(account.operationId()) + || !accountOrder.fenceId().equals(account.fenceId()) + || !accountOrder.actorAccountId().equals(account.input().actorAccountId()) + || !accountOrder.publicationRequestId().equals(intent.publishRequestId()) + || !accountOrder.selectionDigest().equals(selection.digest()) + || !accountOrder.selectedCommitId().equals(selectedCommit.commitId().toString()) + || !accountOrder.bindingDigest().equals(sha256(account.canonicalBytes())) + || !freeze.publicationFence().equals(acknowledgement.publicationFence()) + || !freeze.publicationRequestId().equals(request.publicationRequestId()) + || !freeze.requestDigest().equals(request.requestDigest()) + || !freeze.versionStateEpoch().equals(Long.toString(acknowledgement.versionStateEpoch())) + || !freeze.publishWorkflowId().equals(expectedWorkflow) + || !checkpoint.appliedCommitId().equals(acknowledgement.appliedCommitId()) + || !checkpoint.contentDigest().equals(acknowledgement.contentDigest()) + || checkpoint.digestSchemaVersion() != acknowledgement.digestSchemaVersion() + || !appliedEpochsMatch(selectedCommit, sourceModel.appliedEpochs())) { + throw new IllegalArgumentException( + "World public inventory differs from exact selected Account order or freeze checkpoint"); + } + } + + private static boolean appliedEpochsMatch( + DraftCommitBinding selectedCommit, List actual) { + List expected = + selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + return !expected.isEmpty() && expected.equals(actual); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical lowercase SHA-256"); + } + } + + private static void requireUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static UUID canonicalUuid(String value, String label) { + if (value == null) throw new IllegalArgumentException(label + " is required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static long parsePositiveCanonicalLong(String value, String label) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical positive decimal string"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " is not a canonical positive decimal string"); + } + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(label + " is outside the supported long range", invalid); + } + } + + private static boolean isText(String value) { + return value != null && !value.isBlank() && value.equals(value.strip()); + } + + /** Typed canonical public inventory. This schema intentionally has no private World row keys. */ + public record PublicEvidence( + String schema, + int schemaVersion, + String completeness, + PublicOwnerScope ownerScope, + SelectedApplication selectedApplication, + PublicAccountOrder accountOrder, + Freeze freeze, + Checkpoint checkpoint, + SourceModel sourceModel, + List artifactDecisions) { + public PublicEvidence { + Objects.requireNonNull(schema, "schema"); + Objects.requireNonNull(completeness, "completeness"); + Objects.requireNonNull(ownerScope, "ownerScope"); + Objects.requireNonNull(selectedApplication, "selectedApplication"); + Objects.requireNonNull(accountOrder, "accountOrder"); + Objects.requireNonNull(freeze, "freeze"); + Objects.requireNonNull(checkpoint, "checkpoint"); + Objects.requireNonNull(sourceModel, "sourceModel"); + artifactDecisions = + List.copyOf(Objects.requireNonNull(artifactDecisions, "artifactDecisions")); + requireSupportedProfile( + schema, + schemaVersion, + completeness, + ownerScope, + selectedApplication, + accountOrder, + freeze, + checkpoint, + sourceModel, + artifactDecisions); + } + + public byte[] canonicalBytes() { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(this)); + } catch (IOException failure) { + throw new IllegalStateException("World public inventory could not be encoded", failure); + } + } + + public String digest() { + return sha256(canonicalBytes()); + } + + private static void requireSupportedProfile( + String schema, + int schemaVersion, + String completeness, + PublicOwnerScope owner, + SelectedApplication application, + PublicAccountOrder account, + Freeze freeze, + Checkpoint checkpoint, + SourceModel model, + List artifactDecisions) { + boolean legacyProfile = SCHEMA.equals(schema) && schemaVersion == SCHEMA_VERSION; + boolean inboundClosureProfile = + INBOUND_CLOSURE_SCHEMA.equals(schema) && schemaVersion == INBOUND_CLOSURE_SCHEMA_VERSION; + if ((!legacyProfile && !inboundClosureProfile) + || !"COMPLETE".equals(completeness) + || artifactDecisions.size() != ARTIFACT_DECISIONS.size() + || !artifactDecisions.equals(ARTIFACT_DECISIONS)) { + throw new IllegalArgumentException("Unsupported or incomplete World inventory profile"); + } + requireUuid(owner.canonicalTenantId(), "canonicalTenantId"); + requireUuid(owner.canonicalVersionId(), "canonicalVersionId"); + requireUuid(owner.versionIdentityOperationId(), "versionIdentityOperationId"); + requireUuid(owner.intakeRequestId(), "intakeRequestId"); + requireUuid(owner.intakeOperationId(), "intakeOperationId"); + requireUuid(owner.sourceOperationId(), "sourceOperationId"); + if (!GrpcPeerIdentity.isValidNamespace(owner.targetNamespace()) + || !isText(owner.intakeRequestDigest()) + || !isText(owner.sourceEvidenceDigest()) + || !isText(owner.intakeReceiptDigest())) { + throw new IllegalArgumentException("World public inventory owner scope is incomplete"); + } + requireDigest(owner.intakeRequestDigest(), "intakeRequestDigest"); + requireDigest(owner.sourceEvidenceDigest(), "sourceEvidenceDigest"); + requireDigest(owner.intakeReceiptDigest(), "intakeReceiptDigest"); + + requireUuid(application.applicationOperationId(), "applicationOperationId"); + requireUuid(application.applicationRequestId(), "applicationRequestId"); + canonicalUuid(application.appliedCommitId(), "application.appliedCommitId"); + requireDigest(application.bindingDigest(), "application.bindingDigest"); + requireDigest(application.appliedResultDigest(), "application.appliedResultDigest"); + + requireUuid(account.operationId(), "account.operationId"); + requireUuid(account.fenceId(), "account.fenceId"); + requireUuid(account.actorAccountId(), "account.actorAccountId"); + if (!isText(account.publicationRequestId())) { + throw new IllegalArgumentException("World public Account order is incomplete"); + } + requireDigest(account.selectionDigest(), "account.selectionDigest"); + canonicalUuid(account.selectedCommitId(), "account.selectedCommitId"); + requireDigest(account.bindingDigest(), "account.bindingDigest"); + + requireUuid(freeze.publicationFence(), "publicationFence"); + if (!isText(freeze.publicationRequestId()) || !isText(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("World public freeze binding is incomplete"); + } + if (freeze.requestDigest() == null || !HEX_SHA256.matcher(freeze.requestDigest()).matches()) { + throw new IllegalArgumentException("World freeze request digest must be lowercase SHA-256"); + } + parsePositiveCanonicalLong(freeze.versionStateEpoch(), "versionStateEpoch"); + + canonicalUuid(checkpoint.appliedCommitId(), "checkpoint.appliedCommitId"); + if (checkpoint.contentDigest() == null + || !HEX_SHA256.matcher(checkpoint.contentDigest()).matches() + || checkpoint.digestSchemaVersion() <= 0) { + throw new IllegalArgumentException("World checkpoint is incomplete or malformed"); + } + int requiredCheckpointSchema = inboundClosureProfile ? 4 : 3; + if (checkpoint.digestSchemaVersion() != requiredCheckpointSchema) { + throw new IllegalArgumentException( + "World inventory profile differs from the exact participant digest schema"); + } + + boolean sourceModelMatches = + legacyProfile + ? SOURCE_MODEL.equals(model.modelId()) + && model.graphSchemaVersion() == 2 + && model.inboundSourceClosure() == null + : INBOUND_CLOSURE_SOURCE_MODEL.equals(model.modelId()) + && model.graphSchemaVersion() == INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + && model.inboundSourceClosure() != null; + if (!sourceModelMatches + || !isSha256(model.graphDigest()) + || !isSha256(model.topologyResultDigest()) + || model.generationRuleInputCount() != 0 + || !model.generationRuleFields().equals(GENERATION_RULE_FIELDS) + || !model.regionFields().equals(REGION_FIELDS) + || !model.zoneFields().equals(ZONE_FIELDS) + || !model.roomFields().equals(ROOM_FIELDS) + || !model.roomExitFields().equals(ROOM_EXIT_FIELDS) + || !model.spawnBindingFields().equals(SPAWN_BINDING_FIELDS) + || model.familyCounts().size() != FAMILY_ORDER.size()) { + throw new IllegalArgumentException("World source model is unsupported or incomplete"); + } + if (inboundClosureProfile) { + requireEmptyInboundClosure(model.inboundSourceClosure()); + } + for (int index = 0; index < FAMILY_ORDER.size(); index++) { + FamilyCount count = model.familyCounts().get(index); + if (!FAMILY_ORDER.get(index).equals(count.family()) || count.rowCount() < 0) { + throw new IllegalArgumentException("World source family enumeration is incomplete"); + } + } + int roomCount = familyCount(model.familyCounts(), "ROOM"); + int regionCount = familyCount(model.familyCounts(), "REGION"); + int generationRuleCount = familyCount(model.familyCounts(), "GENERATION_RULE"); + int spawnCount = familyCount(model.familyCounts(), "WORLD_ENTITY_SPAWN_BINDING"); + if (roomCount < 1 + || generationRuleCount != 0 + || model.regionGeneratorInputs().size() != regionCount + || model.generationRuleInputCount() != generationRuleCount + || model.spawnBindingCount() != spawnCount + || model.spawnBindingInputs().size() != spawnCount + || model.appliedEpochs().isEmpty()) { + throw new IllegalArgumentException( + "World source-model counts do not establish completeness"); + } + for (RegionGeneratorInput region : model.regionGeneratorInputs()) { + requireUuid(region.regionTemplateId(), "regionTemplateId"); + if (region.generatorType() == null || region.generatorParams() == null) { + throw new IllegalArgumentException("World region generator inputs must be explicit"); + } + if (!region.generatorType().isEmpty() || !region.generatorParams().isEmpty()) { + throw new IllegalArgumentException( + "Opaque World region generator inputs have no supported requiredness interpretation"); + } + } + requireCanonicalRegionOrder(model.regionGeneratorInputs()); + UUID tenantId = owner.canonicalTenantId(); + UUID versionId = owner.canonicalVersionId(); + for (SpawnBindingInput spawn : model.spawnBindingInputs()) { + requireUuid(spawn.bindingTemplateId(), "spawn.bindingTemplateId"); + requireUuid(spawn.roomTemplateId(), "spawn.roomTemplateId"); + requireUuid(spawn.entityTemplateId(), "spawn.entityTemplateId"); + if (!"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID".equals(spawn.entityReferenceKind()) + || !tenantId.equals(spawn.entityTenantId()) + || !versionId.equals(spawn.entityVersionId()) + || !("ITEM".equals(spawn.entityTemplateType()) + || "NPC".equals(spawn.entityTemplateType())) + || spawn.spawnCount() <= 0 + || spawn.respawnDelaySeconds() < 0) { + throw new IllegalArgumentException( + "World spawn binding is outside the closed supported profile"); + } + } + requireCanonicalSpawnOrder(model.spawnBindingInputs()); + } + + private static void requireCanonicalRegionOrder(List inputs) { + Set seen = new HashSet<>(); + String previous = null; + for (RegionGeneratorInput input : inputs) { + String key = input.regionTemplateId().toString(); + if (!seen.add(input.regionTemplateId()) + || (previous != null && previous.compareTo(key) >= 0)) { + throw new IllegalArgumentException( + "World region generator inputs must have unique canonical UUID order"); + } + previous = key; + } + } + + private static void requireCanonicalSpawnOrder(List inputs) { + Set seen = new HashSet<>(); + String previous = null; + for (SpawnBindingInput input : inputs) { + String key = input.bindingTemplateId().toString(); + if (!seen.add(input.bindingTemplateId()) + || (previous != null && previous.compareTo(key) >= 0)) { + throw new IllegalArgumentException( + "World spawn binding inputs must have unique canonical UUID order"); + } + previous = key; + } + } + + private static int familyCount(List counts, String family) { + return counts.stream() + .filter(count -> family.equals(count.family())) + .mapToInt(FamilyCount::rowCount) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("World inventory omitted family " + family)); + } + + private static boolean isSha256(String value) { + return value != null && SHA256.matcher(value).matches(); + } + } + + public record FamilyCount(String family, int rowCount) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (rowCount < 0) throw new IllegalArgumentException("rowCount must be nonnegative"); + } + } + + public record RegionGeneratorInput( + UUID regionTemplateId, String generatorType, String generatorParams) {} + + public record SpawnBindingInput( + UUID bindingTemplateId, + UUID roomTemplateId, + String entityTemplateType, + String entityReferenceKind, + UUID entityTenantId, + UUID entityVersionId, + UUID entityTemplateId, + int spawnCount, + int respawnDelaySeconds) {} + + public record InboundSourceFamilyCount(String family, int count) { + public InboundSourceFamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("World inbound source count must be nonnegative"); + } + } + } + + public record InboundSourceClosureDeclaration( + int schemaVersion, List familyCounts) { + public InboundSourceClosureDeclaration { + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + } + } + + public record SelectedApplication( + UUID applicationOperationId, + UUID applicationRequestId, + String appliedCommitId, + String bindingDigest, + String appliedResultDigest) {} + + public record PublicAccountOrder( + UUID operationId, + UUID fenceId, + UUID actorAccountId, + String publicationRequestId, + String selectionDigest, + String selectedCommitId, + String bindingDigest) {} + + /** Public World scope; private local tenant/version keys and source-intake rows are omitted. */ + public record PublicOwnerScope( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) {} + + public record Freeze( + UUID publicationFence, + String publicationRequestId, + String requestDigest, + String versionStateEpoch, + String publishWorkflowId) {} + + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) {} + + public record ArtifactDecision(String artifactKind, String state, String rule) { + public ArtifactDecision { + Objects.requireNonNull(artifactKind, "artifactKind"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(rule, "rule"); + } + } + + public record SourceModel( + String modelId, + int graphSchemaVersion, + String graphDigest, + String topologyResultDigest, + List familyCounts, + List regionGeneratorInputs, + List generationRuleFields, + List regionFields, + List zoneFields, + List roomFields, + List roomExitFields, + List spawnBindingFields, + List spawnBindingInputs, + int generationRuleInputCount, + int spawnBindingCount, + List appliedEpochs, + @JsonInclude(JsonInclude.Include.NON_NULL) + InboundSourceClosureDeclaration inboundSourceClosure) { + public SourceModel( + String modelId, + int graphSchemaVersion, + String graphDigest, + String topologyResultDigest, + List familyCounts, + List regionGeneratorInputs, + List generationRuleFields, + List regionFields, + List zoneFields, + List roomFields, + List roomExitFields, + List spawnBindingFields, + List spawnBindingInputs, + int generationRuleInputCount, + int spawnBindingCount, + List appliedEpochs) { + this( + modelId, + graphSchemaVersion, + graphDigest, + topologyResultDigest, + familyCounts, + regionGeneratorInputs, + generationRuleFields, + regionFields, + zoneFields, + roomFields, + roomExitFields, + spawnBindingFields, + spawnBindingInputs, + generationRuleInputCount, + spawnBindingCount, + appliedEpochs, + null); + } + + public SourceModel { + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + regionGeneratorInputs = + List.copyOf(Objects.requireNonNull(regionGeneratorInputs, "regionGeneratorInputs")); + generationRuleFields = + List.copyOf(Objects.requireNonNull(generationRuleFields, "generationRuleFields")); + regionFields = List.copyOf(Objects.requireNonNull(regionFields, "regionFields")); + zoneFields = List.copyOf(Objects.requireNonNull(zoneFields, "zoneFields")); + roomFields = List.copyOf(Objects.requireNonNull(roomFields, "roomFields")); + roomExitFields = List.copyOf(Objects.requireNonNull(roomExitFields, "roomExitFields")); + spawnBindingFields = + List.copyOf(Objects.requireNonNull(spawnBindingFields, "spawnBindingFields")); + spawnBindingInputs = + List.copyOf(Objects.requireNonNull(spawnBindingInputs, "spawnBindingInputs")); + appliedEpochs = List.copyOf(Objects.requireNonNull(appliedEpochs, "appliedEpochs")); + } + } + + private static void requireEmptyInboundClosure(InboundSourceClosureDeclaration declaration) { + if (declaration == null + || declaration.schemaVersion() != 1 + || declaration.familyCounts().size() != INBOUND_SOURCE_FAMILY_ORDER.size()) { + throw new IllegalArgumentException( + "World inbound source closure is not the complete supported version-1 family vector"); + } + for (int index = 0; index < INBOUND_SOURCE_FAMILY_ORDER.size(); index++) { + var count = declaration.familyCounts().get(index); + if (!INBOUND_SOURCE_FAMILY_ORDER.get(index).equals(count.family()) || count.count() != 0) { + throw new IllegalArgumentException( + "World inbound source closure is not canonical or contains unsupported nonempty input"); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java new file mode 100644 index 0000000000..5672a7ac49 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.world.PublishedRealmEntryPolicySetEvidenceTest; +import org.junit.jupiter.api.Test; + +/** Structural retention proof; upstream authority is explicitly stipulated by the fixture. */ +class GameDesignPublicationOperationBindingTest { + @Test + void fiveFramesRetainExactInventoryAndReconstructOriginalFreeze() throws Exception { + var original = PublishedRealmEntryPolicySetEvidenceTest.operation(5L); + var bytes = original.canonicalBytes(); + var frames = new DraftAuthorizationFenceBinding.FrameReader(bytes); + frames.expect("game-design-publication-operation/v2"); + assertThat(frames.bytes()).containsExactly(original.account().canonicalBytes()); + assertThat(frames.bytes()).containsExactly(original.world().canonicalBytes()); + assertThat(frames.bytes()).containsExactly(original.inventory().canonicalBytes()); + assertThat(frames.text()).isEqualTo(original.inventory().digest()); + frames.requireEnd(); + var retained = GameDesignPublicationOperationBinding.fromStored(bytes); + assertThat(retained.canonicalBytes()).containsExactly(bytes); + assertThat(retained.inventory().canonicalBytes()) + .containsExactly(original.inventory().canonicalBytes()); + assertThat(retained.inventory().freezeEvidence().request()) + .isEqualTo(original.inventory().freezeEvidence().request()); + assertThat(retained.inventory().freezeEvidence().acknowledgement()) + .isEqualTo(original.inventory().freezeEvidence().acknowledgement()); + bytes[0] ^= 1; + assertThat(retained.canonicalBytes()).containsExactly(original.canonicalBytes()); + } + + @Test + void absentInventoryWrongDigestTrailingAndOversizeInputsDeny() throws Exception { + var operation = PublishedRealmEntryPolicySetEvidenceTest.operation(5L); + var absent = prefix(operation, GameDesignPublicationOperationBinding.SCHEMA); + assertThatThrownBy(() -> GameDesignPublicationOperationBinding.fromStored(absent.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var wrong = prefix(operation, GameDesignPublicationOperationBinding.SCHEMA); + DraftAuthorizationFenceBinding.frame(wrong, operation.inventory().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(wrong, "sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> GameDesignPublicationOperationBinding.fromStored(wrong.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var trailing = new ByteArrayOutputStream(); + trailing.writeBytes(operation.canonicalBytes()); + trailing.write(0); + assertThatThrownBy( + () -> GameDesignPublicationOperationBinding.fromStored(trailing.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationOperationBinding.fromStored( + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void digestCorrectChangedAppliedOperationAndGraphStillDeny() throws Exception { + var operation = PublishedRealmEntryPolicySetEvidenceTest.operation(5L); + var inventory = operation.inventory().publicEvidence(); + for (String changed : + new String[] { + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + inventory.selectedApplication().appliedResultDigest(), + "sha256:" + "0".repeat(64)), + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace(inventory.sourceModel().graphDigest(), "sha256:" + "1".repeat(64)), + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + inventory.selectedApplication().applicationOperationId().toString(), + java.util.UUID.randomUUID().toString()) + }) { + var bytes = changed.getBytes(StandardCharsets.UTF_8); + var digest = + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + operation.account(), operation.world(), bytes, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void historicalThreeFramePreimageRetainsExactBytesWithoutInventoryAuthority() throws Exception { + var fresh = PublishedRealmEntryPolicySetEvidenceTest.operation(5L); + // Independently reproduce the original v1 preimage, without using the current encoder. + var original = prefix(fresh, "game-design-publication-operation/v1").toByteArray(); + var retained = GameDesignPublicationOperationBinding.fromStored(original); + assertThat(retained.account().canonicalBytes()) + .containsExactly(fresh.account().canonicalBytes()); + assertThat(retained.world().canonicalBytes()).containsExactly(fresh.world().canonicalBytes()); + assertThat(retained.canonicalBytes()).containsExactly(original); + assertThat(retained).isEqualTo(GameDesignPublicationOperationBinding.fromStored(original)); + assertThat(retained.hashCode()) + .isEqualTo(GameDesignPublicationOperationBinding.fromStored(original).hashCode()); + assertThat(retained).isNotEqualTo(fresh); + assertThatThrownBy(retained::inventory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + assertThatThrownBy( + () -> new GameDesignPublicationOperationBinding(fresh.account(), fresh.world(), null)) + .isInstanceOf(NullPointerException.class); + original[0] ^= 1; + assertThat(retained.canonicalBytes()) + .containsExactly(prefix(fresh, "game-design-publication-operation/v1").toByteArray()); + } + + @Test + void malformedAndMismatchedHistoricalInputsDeny() throws Exception { + var fresh = PublishedRealmEntryPolicySetEvidenceTest.operation(5L); + var trailing = prefix(fresh, "game-design-publication-operation/v1"); + trailing.write(0); + assertThatThrownBy( + () -> GameDesignPublicationOperationBinding.fromStored(trailing.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var missing = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(missing, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(missing, fresh.account().canonicalBytes()); + assertThatThrownBy( + () -> GameDesignPublicationOperationBinding.fromStored(missing.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var mismatched = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(mismatched, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(mismatched, fresh.account().canonicalBytes()); + String changedWorld = + new String(fresh.world().canonicalBytes(), StandardCharsets.UTF_8) + .replace( + fresh.world().request().publicationRequestId(), + "changed-" + fresh.world().request().publicationRequestId()); + assertThat(changedWorld) + .isNotEqualTo(new String(fresh.world().canonicalBytes(), StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(mismatched, changedWorld.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> GameDesignPublicationOperationBinding.fromStored(mismatched.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static ByteArrayOutputStream prefix( + GameDesignPublicationOperationBinding operation, String schema) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.world().canonicalBytes()); + return out; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 91e1b4d921..53c24b811b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -38,7 +38,7 @@ import tools.jackson.databind.node.ObjectNode; /** Fixed isolated fixtures prove carrier integrity, not owner producer, database, or mTLS proof. */ -class PublishedRealmEntryPolicySetEvidenceTest { +public class PublishedRealmEntryPolicySetEvidenceTest { private static final String DIGEST = "sha256:" + "a".repeat(64); private static final ObjectMapper JSON = new ObjectMapper(); @@ -639,7 +639,7 @@ static ReleaseContent release( operation.world()); } - static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { + public static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { var seed = AuthoringFixtures.startLocationEvidence(); var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = @@ -707,7 +707,11 @@ static GameDesignPublicationOperationBinding operation(long epoch) throws Except seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), seed.appliedResultBytes()); - return new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationOperationBinding( + account, + world, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, world)); } private static UUID uuid(String value) { diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java new file mode 100644 index 0000000000..d529ad025a --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.test; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +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.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * ISOLATED stipulated external COMPLETE evidence for local consumer tests only. This does not + * execute World's source inventory producer or establish actual graph requiredness/completeness. + * Actual World persistence tests must use their real retained inventory instead. + */ +public final class IsolatedWorldPublicationInventoryFixtures { + private IsolatedWorldPublicationInventoryFixtures() {} + + public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + var selected = account.input().selection(); + var commit = selected.selectedCommit(); + var request = world.request(); + var original = DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var graph = + WorldDraftStartLocationEvidence.fromStored(world.selectorReceiptBytes()).graphDigest(); + boolean closureQualified = request.digestSchemaVersion() == 4; + String inventorySchema = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA; + int inventorySchemaVersion = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA_VERSION; + String sourceModel = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL + : WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL; + int graphSchemaVersion = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + : 2; + var inboundClosure = + closureQualified + ? new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration( + 1, + List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))) + : null; + UUID fixtureId = + UUID.nameUUIDFromBytes("ISOLATED World inventory input".getBytes(StandardCharsets.UTF_8)); + var evidence = + new PublicEvidence( + inventorySchema, + inventorySchemaVersion, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + fixtureId, + request.intakeRequestId(), + fixtureId, + sha256(world.originalAccountBindingBytes()), + fixtureId, + sha256(world.selectorReceiptBytes()), + sha256(world.selectorReceiptBytes())), + new SelectedApplication( + original.operationId(), + commit.requestId(), + commit.commitId().toString(), + commit.digest(), + sha256(world.appliedResultBytes())), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selected.intent().publishRequestId(), + selected.digest(), + commit.commitId().toString(), + sha256(account.canonicalBytes())), + new Freeze( + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(request.versionStateEpoch()), + request.publishWorkflowId()), + new Checkpoint( + request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion()), + new SourceModel( + sourceModel, + graphSchemaVersion, + graph, + sha256("ISOLATED topology result".getBytes(StandardCharsets.UTF_8)), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(fixtureId, "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()) + .add(BigInteger.ONE) + .toString())) + .toList(), + inboundClosure), + List.of( + new ArtifactDecision( + "NAVMESH", + "NOT_REQUIRED", + "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + return WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, evidence.canonicalBytes(), evidence.digest()); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} 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 index e1d831cce1..3377efb694 100644 --- 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 @@ -8,11 +8,13 @@ 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.AssetSnapshot; 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"; + public static final String SCHEMA = "game-design-reviewed-draft-base/v2"; + public static final String HISTORICAL_SCHEMA = "game-design-reviewed-draft-base/v1"; private final TargetProof target; private final DraftBaseReference reference; private final byte[] bytes; @@ -41,11 +43,13 @@ private GameDesignReviewedBaseEvidence( public static GameDesignReviewedBaseEvidence genesis(GameDesignSourceRepository.Genesis genesis) { Objects.requireNonNull(genesis, "genesis"); + AssetSnapshot.Genesis asset = genesis.asset(); ByteArrayOutputStream out = new ByteArrayOutputStream(); - frame(out, "shared-policy-command-genesis/v1"); + frame(out, "shared-policy-command-asset-genesis/v2"); frame(out, genesis.policy().creationTransactionId()); DraftAuthorizationFenceBinding.frame(out, genesis.policy().canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, genesis.command().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, asset.canonicalBytes()); return new GameDesignReviewedBaseEvidence( genesis.policy().target(), new DraftBaseReference(DraftBaseReference.Kind.GENESIS, genesis.policy().receiptId()), @@ -57,6 +61,9 @@ public static GameDesignReviewedBaseEvidence authored( DraftCommitCoordinatorRepository.CommitSnapshot retained) { Objects.requireNonNull(sources, "sources"); Objects.requireNonNull(retained, "retained"); + if (sources.assetEvidence().isEmpty()) { + throw new IllegalArgumentException("Reviewed authored base requires retained asset lineage"); + } DraftCommitBinding binding = sources.command().binding(); if (!binding.equals(retained.binding()) || retained.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED @@ -65,10 +72,11 @@ public static GameDesignReviewedBaseEvidence authored( "Exact retained synchronized base and owner vector required"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); - frame(out, "retained-authored-policy-command-base/v1"); + frame(out, "retained-authored-policy-command-asset-base/v2"); DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, sources.policy().canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, sources.command().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, sources.asset().canonicalBytes()); frame(out, Integer.toString(binding.requiredOwners().size())); for (var owner : binding.requiredOwners()) { var state = retained.ownerStates().get(owner); 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 index 56439d2c92..6995dc8f3a 100644 --- 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 @@ -134,13 +134,18 @@ public Optional read(DraftCommitBinding binding) { || !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))) { + || !isSupportedSchema(row.get("evidence_schema", String.class))) { throw new IllegalArgumentException("REVIEWED_BASE_STORED_BINDING_CONFLICT"); } + String evidenceSchema = row.get("evidence_schema", String.class); + byte[] evidenceBytes = row.get("evidence_bytes", byte[].class); + if (!evidenceSchema.equals( + new DraftAuthorizationFenceBinding.FrameReader(evidenceBytes).text())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); + } var result = new ReviewedBaseReadback( - row.get("evidence_bytes", byte[].class), row.get("evidence_digest", String.class)); + evidenceBytes, row.get("evidence_digest", String.class), evidenceSchema); return Optional.of(result); } @@ -161,6 +166,20 @@ public ReviewedBaseReadback requireRetained(DraftCommitBinding binding) { return retained; } + /** Current writes require evidence framed with the asset-bound v2 schema. */ + public ReviewedBaseReadback requireCurrentRetained(DraftCommitBinding binding) { + ReviewedBaseReadback retained = requireRetained(binding); + if (!GameDesignReviewedBaseEvidence.SCHEMA.equals(retained.schema())) { + throw new IllegalStateException("REVIEWED_BASE_ASSET_LINEAGE_UNAVAILABLE"); + } + return retained; + } + + private static boolean isSupportedSchema(String schema) { + return GameDesignReviewedBaseEvidence.SCHEMA.equals(schema) + || GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA.equals(schema); + } + private void lockDraft(TargetProof target) { Objects.requireNonNull(target, "target"); var version = @@ -192,14 +211,21 @@ private static void requireWrite() { } } - public record ReviewedBaseReadback(byte[] canonicalBytes, String digest) { + public record ReviewedBaseReadback(byte[] canonicalBytes, String digest, String schema) { public ReviewedBaseReadback { canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + schema = Objects.requireNonNull(schema, "schema"); + if (!isSupportedSchema(schema)) + throw new IllegalArgumentException("Unsupported reviewed-base evidence schema"); if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(digest)) { throw new IllegalArgumentException("REVIEWED_BASE_STORED_DIGEST_CONFLICT"); } } + public ReviewedBaseReadback(byte[] canonicalBytes, String digest) { + this(canonicalBytes, digest, GameDesignReviewedBaseEvidence.SCHEMA); + } + @Override public byte[] canonicalBytes() { return canonicalBytes.clone(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java new file mode 100644 index 0000000000..aca551643e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact ordinary-source application evidence, composed into one control-plane owner result. */ +public record AssetApplication( + DraftCommitBinding binding, String expectedEpoch, AssetSnapshot snapshot) { + public AssetApplication { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || AssetSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Ordinary asset application must advance its exact bound epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + AssetSource.SCOPE, + binding.target().canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-ordinary-asset-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java new file mode 100644 index 0000000000..bc5371d87a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.List; +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.gamedesign.AssetSnapshot.Item; +import net.firedevops.firemud.common.gamedesign.CommandSource; + +/** Ordinary selected source only; no total inventory or template/branding completeness claim. */ +public record AssetSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public AssetSnapshot { + var value = + new net.firedevops.firemud.common.gamedesign.AssetSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + items = value.items(); + } + + @Override + public List items() { + return List.copyOf(items); + } + + public String canonicalJson() { + return shared().canonicalJson(); + } + + public byte[] canonicalBytes() { + return shared().canonicalBytes(); + } + + public String digest() { + return shared().digest(); + } + + public static AssetSnapshot fromStored(String json) { + return fromShared(net.firedevops.firemud.common.gamedesign.AssetSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.AssetSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.AssetSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + } + + public static AssetSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.AssetSnapshot value) { + return new AssetSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.items()); + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + if (receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Exact ordinary source creation evidence required"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-ordinary-asset-source-genesis/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, + net.firedevops.firemud.common.gamedesign.CommandSource.canonical( + net.firedevops.firemud.common.gamedesign.CommandSource.targetObject(target))); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, receiptId.toString()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, creationTransactionId); + return out.toByteArray(); + } + } + + public record Capture(GameDesignPublicationOperation operation, AssetSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException("Ordinary asset capture differs from selected commit"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-ordinary-asset-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()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java new file mode 100644 index 0000000000..7cae074cca --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -0,0 +1,596 @@ +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.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +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; + +/** + * Actual ordinary source writes under the existing coordinator; never total inventory authority. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local injected persistence collaborator") +public final class AssetSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public AssetSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public AssetSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var policyGenesis = + new RealmPolicySourceRepository(dsl) + .readGenesis(target) + .orElseThrow( + () -> new IllegalStateException("ASSET_SOURCE_POLICY_GENESIS_UNAVAILABLE")); + var prior = readGenesis(target); + if (prior.isPresent()) { + var retained = prior.orElseThrow(); + if (!policyGenesis.creationTransactionId().equals(retained.creationTransactionId())) { + throw new IllegalStateException("ASSET_SOURCE_GENESIS_IDENTITY_CONFLICT"); + } + return retained; + } + 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("ASSET_SOURCE_FRESH_INSERT_UNAVAILABLE"); + String creationTransactionId = witness.get(0, String.class); + if (!policyGenesis.creationTransactionId().equals(creationTransactionId)) { + throw new IllegalStateException("ASSET_SOURCE_CREATION_WITNESS_CONFLICT"); + } + var genesis = + new AssetSnapshot.Genesis(target, UUID.randomUUID(), policyGenesis.creationTransactionId()); + dsl.execute( + "INSERT INTO game_design_asset_source_genesis " + + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + genesis.receiptId(), + genesis.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target))); + dsl.execute( + "INSERT INTO game_design_asset_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + genesis.receiptId()); + if (!genesis.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_READBACK_CONFLICT"); + return genesis; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new AssetSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var mutations = AssetSource.mutations(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!binding.requestId().equals(slot.requestId()) + || !binding.commitId().equals(slot.commitId()) + || owner == null + || (owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) + throw new IllegalStateException("ASSET_SOURCE_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(AssetSourceRepository::isScope) + .toList(); + String epoch = head.get("source_epoch", String.class); + if (units.size() != 1 + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("ASSET_SOURCE_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + requirePreviousFence(binding.target(), inherited); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + if (inherited == null && !"0".equals(epoch)) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_NOT_CURRENT"); + // Lock all actual source rows in owner-key order before writing any revision history. + mutations.stream() + .filter(m -> m.operation() == AssetSource.OperationKind.UPSERT) + .map(m -> Long.parseLong(m.assetRowId())) + .distinct() + .sorted() + .forEach( + id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("ASSET_SOURCE_ROW_UNAVAILABLE"); + }); + for (var mutation : mutations) { + net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item item = + mutation.operation() == AssetSource.OperationKind.UPSERT + ? qualify( + new AssetSource.Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()), + true) + : null; + dsl.execute( + "INSERT INTO game_design_asset_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, usage_key, asset_id, requiredness, content_type, content_digest, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + mutation.usageKey(), + item == null ? null : Long.parseLong(mutation.assetRowId()), + item == null ? null : mutation.requiredness().name(), + item == null ? null : item.contentType(), + item == null ? null : item.contentDigest(), + item == null ? null : item.byteSize()); + } + var references = + AssetSource.replay( + previous.stream() + .map(net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item::reference) + .toList(), + binding) + .references(); + var snapshot = + new AssetSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + references.stream().map(r -> qualify(r, false)).toList()); + var result = new AssetApplication(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_asset_source_application " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_asset_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 CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("ASSET_SOURCE_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public AssetSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = readSnapshot(binding.target(), binding.commitId()); + if (prior.isPresent()) { + if (!prior.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + return prior.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + AssetSnapshot snapshot; + if (!AssetSource.mutations(binding).isEmpty()) { + var result = + applied.orElseThrow( + () -> new IllegalStateException("ASSET_SOURCE_APPLICATION_UNAVAILABLE")); + snapshot = result.snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("ASSET_SOURCE_PREDECESSOR_CHANGED"); + } else { + var items = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + snapshot = + new AssetSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + items); + } + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("ASSET_SOURCE_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_asset_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + dsl.execute( + "UPDATE game_design_asset_source_head 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 Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json, snapshot_digest FROM game_design_asset_source_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 = AssetSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_READBACK_CONFLICT"); + exact(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 request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) { + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyItems(snapshot); + if (dsl.fetchOne( + "SELECT 1 FROM game_design_asset_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND visible_commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId) + != null) { + var mappings = + dsl.fetch( + "SELECT asset_id, usage_key, usage_type FROM version_asset WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()); + if (mappings.size() != snapshot.items().size() + || mappings.stream() + .anyMatch( + mapping -> + mapping.get("usage_type") != null + || snapshot.items().stream() + .noneMatch( + item -> + item.reference() + .assetRowId() + .equals( + mapping.get("asset_id", Long.class).toString()) + && item.reference() + .usageKey() + .equals(mapping.get("usage_key", String.class))))) { + throw new IllegalStateException("ASSET_SOURCE_PROJECTION_READBACK_CONFLICT"); + } + } + return Optional.of(snapshot); + } + + public AssetSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("ASSET_SOURCE_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("ASSET_SOURCE_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("ASSET_SOURCE_NOT_SYNCHRONIZED"); + var capture = new AssetSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_asset_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture(GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new AssetSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("ASSET_SOURCE_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + /** + * Requires actual synchronized source, including empty ordinary sets; never invents a baseline. + */ + public AssetSnapshot requireExportSelection(String tenantId, long versionId) { + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(); + var canonical = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + version.getCanonicalTenantId(), version.getCanonicalVersionId()) + .orElseThrow(() -> new IllegalStateException("ASSET_SOURCE_TARGET_UNQUALIFIED")); + if (!version.getId().equals(canonical.getId())) + throw new IllegalStateException("ASSET_SOURCE_TARGET_CHANGED"); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + versionId, + tenantId, + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var head = readHead(target, false); + UUID commit = head.get("visible_commit_id", UUID.class); + if (commit == null) + throw new IllegalStateException("ASSET_SOURCE_SYNCHRONIZED_SELECTION_UNAVAILABLE"); + var snapshot = readSnapshot(target, commit).orElseThrow(); + requireFence(snapshot.binding()); + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("ASSET_SOURCE_NOT_SYNCHRONIZED"); + return snapshot; + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_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(); + var result = + new AssetApplication( + binding, + row.get("expected_epoch", String.class), + AssetSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class)) + || !binding.requestId().equals(row.get("request_id", UUID.class))) + throw new IllegalStateException("ASSET_SOURCE_APPLICATION_READBACK_CONFLICT"); + verifyItems(result.snapshot()); + return Optional.of(result); + } + + private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualify( + AssetSource.Reference reference, boolean lock) { + var target = reference.sourceBinding().target(); + var row = + dsl.fetchOne( + "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?" + + (lock ? " FOR UPDATE" : ""), + target.gameDesignVersionTenantKey(), + Long.parseLong(reference.assetRowId())); + if (row == null + || !reference.usageKey().equals(row.get("file_name", String.class)) + || row.get("data", byte[].class) == null) + throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); + byte[] bytes = row.get("data", byte[].class); + return new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, + row.get("content_type", String.class), + CommandSource.sha256(bytes), + bytes.length); + } + + private void verifyItems(AssetSnapshot snapshot) { + for (var item : snapshot.items()) { + if (!item.equals(qualify(item.reference(), false))) + throw new IllegalStateException("ASSET_SOURCE_BYTE_READBACK_CONFLICT"); + var r = item.reference(); + var row = + dsl.fetchOne( + "SELECT content_digest, content_type, byte_size FROM game_design_asset_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND commit_id = ? AND request_id = ? AND revision_order = ? AND asset_id = ? AND usage_key = ? AND requiredness = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + r.revisionId(), + r.sourceBinding().commitId(), + r.sourceBinding().requestId(), + Integer.parseInt(r.revisionOrder()), + Long.parseLong(r.assetRowId()), + r.usageKey(), + r.requiredness().name()); + if (row == null + || !item.contentDigest().equals(row.get("content_digest", String.class)) + || !item.contentType().equals(row.get("content_type", String.class)) + || item.byteSize() != row.get("byte_size", Long.class)) + throw new IllegalStateException("ASSET_SOURCE_REVISION_READBACK_CONFLICT"); + } + } + + private Record head(TargetProof target) { + return readHead(target, true); + } + + private Record readHead(TargetProof target, boolean lock) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("ASSET_SOURCE_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (lock ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()), + "ASSET_SOURCE_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("ASSET_SOURCE_BINDING_CHANGED"); + } + + private void requirePreviousFence(TargetProof target, UUID inherited) { + var fence = coordinator.readVisibilityFence(target); + if (inherited == null + ? fence.isPresent() + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("ASSET_SOURCE_PREVIOUS_FENCE_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("ASSET_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null + || dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()) + != null) throw new IllegalStateException("ASSET_SOURCE_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var qualified = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("ASSET_SOURCE_TARGET_CHANGED"); + } + + static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return AssetSource.SCOPE.equals(unit.aggregateType()) + && AssetSource.SCOPE.equals(unit.scopeType()) + && AssetSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Ordinary asset source requires writable READ_COMMITTED transaction"); + } +} 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 index e833008d33..870e5b0bf0 100644 --- 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 @@ -16,6 +16,7 @@ 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.gamedesign.AssetSource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @@ -141,9 +142,9 @@ public String digest() { } /** - * 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. + * Converts the closed Draft owner payloads to command mutations. Realm policy and ordinary asset + * reference payloads are separate Game Design owner scopes and are left to their typed writers. + * Unknown kinds deny rather than being guessed from omitted or legacy rows. */ public static List mutations(DraftCommitBinding binding) { Objects.requireNonNull(binding, "binding"); @@ -155,7 +156,8 @@ public static List mutations(DraftCommitBinding binding) { 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 (REALM_POLICY_REVISION_KIND.equals(revisionKind) + || AssetSource.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -204,7 +206,8 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { String revisionKind = payload.path("revisionKind").asText(); if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { found = true; - } else if (!REVISION_KIND.equals(revisionKind)) { + } else if (!REVISION_KIND.equals(revisionKind) + && !AssetSource.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } 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 index ffc60d15a4..6785785d51 100644 --- 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 @@ -9,6 +9,7 @@ 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.AssetSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; import org.jooq.DSLContext; @@ -125,7 +126,8 @@ public Optional apply(DraftCommitBinding binding) { exactCommit(binding); List mutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); - requireCompleteControlPlaneScopes(binding, mutations, policyMutation); + boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + requireCompleteControlPlaneScopes(binding, mutations, policyMutation, assetMutation); Optional existing = application(binding); if (existing.isPresent()) return existing; if (mutations.isEmpty()) return Optional.empty(); @@ -217,7 +219,10 @@ public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { String sourceEpoch = head.get("source_epoch", String.class); List mutations = CommandSource.mutations(binding); requireCompleteControlPlaneScopes( - binding, mutations, CommandSource.hasRealmPolicyRevision(binding)); + binding, + mutations, + CommandSource.hasRealmPolicyRevision(binding), + !AssetSource.mutations(binding).isEmpty()); List definitions; if (!mutations.isEmpty()) { CommandApplication applied = @@ -541,21 +546,26 @@ private void verifyDefinitionProvenance(CommandSnapshot snapshot) { private void requireCompleteControlPlaneScopes( DraftCommitBinding binding, List commandMutations, - boolean policyMutation) { + boolean policyMutation, + boolean assetMutation) { 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(); + List assets = + units.stream().filter(AssetSourceRepository::isScope).toList(); if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) - || commands.size() + policies.size() != units.size()) { + || assets.size() != (assetMutation ? 1 : 0) + || commands.size() + policies.size() + assets.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()); + if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); } private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { 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 index 45d095299a..4689d55724 100644 --- 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 @@ -2,41 +2,70 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; 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 final class GameDesignPublicationOperation { public static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; + private final GameDesignPublicationOperationBinding binding; - public GameDesignPublicationOperation { - var binding = new GameDesignPublicationOperationBinding(account, world); - account = binding.account(); - world = binding.world(); + public GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory) { + this(new GameDesignPublicationOperationBinding(account, world, inventory)); + } + + private GameDesignPublicationOperation(GameDesignPublicationOperationBinding binding) { + this.binding = binding; + } + + public AccountPublicationAuthorizationBinding account() { + return binding.account(); + } + + public WorldPublishedStartLocationEvidence world() { + return binding.world(); + } + + public WorldSelectedPublicationArtifactInventoryEvidence inventory() { + return binding.inventory(); } public byte[] canonicalBytes() { - return new GameDesignPublicationOperationBinding(account, world).canonicalBytes(); + return binding.canonicalBytes(); + } + + @Override + public boolean equals(Object other) { + return other instanceof GameDesignPublicationOperation operation + && binding.equals(operation.binding); + } + + @Override + public int hashCode() { + return binding.hashCode(); } public static GameDesignPublicationOperation fromStored(byte[] bytes) { - var binding = GameDesignPublicationOperationBinding.fromStored(bytes); - return new GameDesignPublicationOperation(binding.account(), binding.world()); + return new GameDesignPublicationOperation( + GameDesignPublicationOperationBinding.fromStored(bytes)); } public String workflowId() { - return world.request().publishWorkflowId(); + return world().request().publishWorkflowId(); } public String tenantKey() { - return account.input().selection().target().gameDesignVersionTenantKey(); + return account().input().selection().target().gameDesignVersionTenantKey(); } public long versionId() { - return account.input().selection().target().gameDesignVersionRowId(); + return account().input().selection().target().gameDesignVersionRowId(); } public String selectionDigest() { - return account.input().selection().digest(); + return account().input().selection().digest(); } } 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 index e7c3ab067a..1435552d5e 100644 --- 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 @@ -2,6 +2,7 @@ import java.io.ByteArrayOutputStream; import java.util.Arrays; +import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -11,6 +12,7 @@ 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.gamedesign.AssetSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; @@ -23,17 +25,25 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Joins the two actual Game Design sources under one caller-owned coordinator transaction. */ +/** Joins command, policy, and ordinary asset sources under one coordinator transaction. */ public final class GameDesignSourceRepository { + 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 RealmPolicySourceRepository policies; private final CommandSourceRepository commands; + private final AssetSourceRepository assets; private final DraftCommitCoordinatorRepository coordinator; public GameDesignSourceRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "dsl"); policies = new RealmPolicySourceRepository(dsl); commands = new CommandSourceRepository(dsl); + assets = new AssetSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); } @@ -56,7 +66,8 @@ public Genesis enrollFreshDraft(TargetProof target) { commands.enrollNewDraftGenesis( new CommandSource.NewDraftGenesisReceipt( target, policy.receiptId(), policy.creationTransactionId())); - Genesis result = new Genesis(policy, command); + AssetSnapshot.Genesis asset = assets.enrollFreshDraft(target); + Genesis result = new Genesis(policy, command, Optional.of(asset)); if (!result.equals( readGenesis(target) .orElseThrow( @@ -72,11 +83,12 @@ 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(); + var asset = assets.readGenesis(target); + if (policy.isEmpty() && command.isEmpty() && asset.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())); + return Optional.of(new Genesis(policy.orElseThrow(), command.orElseThrow(), asset)); } /** Stage actual source writes and record exactly one complete local owner outcome. */ @@ -85,23 +97,68 @@ public Application apply(DraftCommitBinding binding) { Objects.requireNonNull(binding, "binding"); List commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); - requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation); + boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation, assetMutation); requireGenesis(binding.target()); requireReviewed(binding); Optional command = commands.apply(binding); if (command.isPresent() != !commandMutations.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_COMMAND_APPLICATION_INCOMPLETE"); } + Optional asset = assets.apply(binding); + if (asset.isPresent() != assetMutation) { + throw new IllegalStateException("GAME_DESIGN_ASSET_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. + // first, then records the combined result using actual sibling readback bytes. policy = Optional.of( - command.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); + command.isPresent() || asset.isPresent() + ? policies.applyMutation(binding) + : policies.apply(binding)); } OwnerOutcome expected; - if (policy.isPresent() && command.isPresent()) { + if (asset.isPresent()) { + ByteArrayOutputStream components = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + components, "game-design-control-plane-sibling-components/v1"); + List epochs = new java.util.ArrayList<>(); + if (command.isPresent()) { + DraftAuthorizationFenceBinding.frame(components, "COMMAND"); + DraftAuthorizationFenceBinding.frame(components, command.orElseThrow().canonicalBytes()); + epochs.add(command.orElseThrow().commandAppliedEpoch()); + } + DraftAuthorizationFenceBinding.frame(components, "ASSET"); + DraftAuthorizationFenceBinding.frame(components, asset.orElseThrow().canonicalBytes()); + epochs.add(asset.orElseThrow().appliedEpoch()); + if (policy.isPresent()) { + var policyResult = policy.orElseThrow(); + epochs.add(policyResult.ownerOutcome().appliedEpochs().getFirst()); + epochs.sort(APPLIED_EPOCH_ORDER); + List orderedEpochs = List.copyOf(epochs); + policies.recordCombinedOwnerOutcome(binding, components.toByteArray(), orderedEpochs); + expected = policyResult.combinedOwnerOutcome(components.toByteArray(), orderedEpochs); + } else { + epochs.sort(APPLIED_EPOCH_ORDER); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + out, "game-design-control-plane-ordinary-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, components.toByteArray()); + expected = + new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ordinary-source:" + binding.commitId(), + out.toByteArray(), + List.copyOf(epochs)); + coordinator.recordOwnerOutcome(binding, expected); + } + } else if (policy.isPresent() && command.isPresent()) { var policyResult = policy.orElseThrow(); var commandResult = command.orElseThrow(); List epochs = @@ -129,7 +186,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, retained); + return new Application(binding, command, policy, asset, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -140,16 +197,20 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { requireReviewed(binding); CommandSnapshot command = commands.captureSynchronized(binding); RealmPolicySnapshot policy = policies.captureSynchronized(binding); - if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { + AssetSnapshot asset = assets.captureSynchronized(binding); + if (!binding.equals(command.binding()) + || !binding.equals(policy.binding()) + || !binding.equals(asset.binding())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); } - return new SynchronizedSources(command, policy); + return new SynchronizedSources(command, policy, Optional.of(asset)); } - /** Freeze both complete, selected source snapshots against the same retained operation. */ + /** Freeze complete selected source snapshots against the same current retained operation. */ public Capture freeze(GameDesignPublicationOperation operation) { requireWrite(); Objects.requireNonNull(operation, "operation"); + requireCurrentOperation(operation); requireGenesis(operation.account().input().selection().target()); requireReviewed(operation.account().input().selection().selectedCommit()); RealmPolicySnapshot.Capture policy; @@ -161,13 +222,18 @@ public Capture freeze(GameDesignPublicationOperation operation) { "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); + AssetSnapshot.Capture asset = assets.freeze(operation); + Capture result = new Capture(command, policy, Optional.of(asset)); 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())) { + || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes()) + || retained.asset().isEmpty() + || !Arrays.equals( + result.asset().orElseThrow().canonicalBytes(), + retained.asset().orElseThrow().canonicalBytes())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); } return retained; @@ -176,14 +242,20 @@ public Capture freeze(GameDesignPublicationOperation operation) { /** 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()); + boolean historical = isHistoricalOperation(operation); + if (!historical) 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()) { + var asset = assets.readCapture(operation); + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); + if (historical) { + new GameDesignReviewedBaseRepository(dsl) + .requireRetained(operation.account().input().selection().selectedCommit()); + } + if (command.isEmpty() || policy.isEmpty() || asset.isEmpty() && !historical) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } - return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow())); + return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow(), asset)); } public Optional readSynchronized(TargetProof target, UUID commitId) { @@ -191,21 +263,38 @@ public Optional readSynchronized(TargetProof target, UUID c Objects.requireNonNull(commitId, "commitId"); var command = commands.readSnapshot(target, commitId); var policy = policies.readSnapshot(target, commitId); - if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + var asset = assets.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty() && asset.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())); + var binding = command.orElseThrow().binding(); + boolean assetGenesisRetained = assets.readGenesis(target).isPresent(); + if (asset.isEmpty() && (assetGenesisRetained || !AssetSource.mutations(binding).isEmpty())) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); + } + return Optional.of(new SynchronizedSources(command.orElseThrow(), policy.orElseThrow(), asset)); } private void requireGenesis(TargetProof target) { - if (readGenesis(target).isEmpty()) { + if (readGenesis(target).filter(genesis -> genesis.assetEvidence().isPresent()).isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); } } private void requireReviewed(DraftCommitBinding binding) { - new GameDesignReviewedBaseRepository(dsl).requireRetained(binding); + new GameDesignReviewedBaseRepository(dsl).requireCurrentRetained(binding); + } + + private static void requireCurrentOperation(GameDesignPublicationOperation operation) { + if (isHistoricalOperation(operation)) { + throw new IllegalStateException("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + } + } + + private static boolean isHistoricalOperation(GameDesignPublicationOperation operation) { + return "game-design-publication-operation/v1" + .equals(new DraftAuthorizationFenceBinding.FrameReader(operation.canonicalBytes()).text()); } private static OwnerOutcome commandOnlyOutcome( @@ -225,8 +314,8 @@ private static OwnerOutcome commandOnlyOutcome( } private static void requireCompleteScopes( - DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy) { - if (!hasCommand && !hasPolicy + DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy, boolean hasAsset) { + if (!hasCommand && !hasPolicy && !hasAsset || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -247,9 +336,11 @@ private static void requireCompleteScopes( && RealmPolicySource.SCOPE.equals(unit.scopeType()) && "effective".equals(unit.scopeId())) .toList(); + List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) - || commands.size() + policies.size() != units.size() + || assets.size() != (hasAsset ? 1 : 0) + || commands.size() + policies.size() + assets.size() != units.size() || units.stream() .anyMatch( unit -> @@ -274,31 +365,52 @@ private static void requireWrite() { } } - public record Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + public record Genesis( + RealmPolicyGenesis policy, + CommandSource.NewDraftGenesisReceipt command, + Optional assetEvidence) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); + assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); if (!policy.target().equals(command.target()) || !policy.receiptId().equals(command.receiptId()) - || !policy.creationTransactionId().equals(command.creationTransactionId())) { + || !policy.creationTransactionId().equals(command.creationTransactionId()) + || assetEvidence.isPresent() + && (!policy.target().equals(assetEvidence.orElseThrow().target()) + || !policy + .creationTransactionId() + .equals(assetEvidence.orElseThrow().creationTransactionId()))) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); } } + + public Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + this(policy, command, Optional.empty()); + } + + public AssetSnapshot.Genesis asset() { + return assetEvidence.orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_ASSET_GENESIS_UNAVAILABLE")); + } } public record Application( DraftCommitBinding binding, Optional command, Optional policy, + Optional asset, OwnerOutcome ownerOutcome) { public Application { Objects.requireNonNull(binding, "binding"); command = Objects.requireNonNull(command, "command"); policy = Objects.requireNonNull(policy, "policy"); + asset = Objects.requireNonNull(asset, "asset"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); - if (command.isEmpty() && policy.isEmpty() + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) + || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -308,22 +420,43 @@ public record Application( } } - public record SynchronizedSources(CommandSnapshot command, RealmPolicySnapshot policy) { + public record SynchronizedSources( + CommandSnapshot command, RealmPolicySnapshot policy, Optional assetEvidence) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); - if (!command.binding().equals(policy.binding())) { + assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); + if (!command.binding().equals(policy.binding()) + || assetEvidence.isPresent() + && !command.binding().equals(assetEvidence.orElseThrow().binding())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); } } + + public AssetSnapshot asset() { + return assetEvidence.orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_ASSET_SOURCE_UNAVAILABLE")); + } } - public record Capture(CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy) { + public record Capture( + CommandSnapshot.Capture command, + RealmPolicySnapshot.Capture policy, + Optional asset) { public Capture { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); + asset = Objects.requireNonNull(asset, "asset"); if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) - || !command.snapshot().binding().equals(policy.snapshot().binding())) { + || !command.snapshot().binding().equals(policy.snapshot().binding()) + || asset.isPresent() + && (!Arrays.equals( + command.operation().canonicalBytes(), + asset.orElseThrow().operation().canonicalBytes()) + || !command + .snapshot() + .binding() + .equals(asset.orElseThrow().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/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 9d652b0313..ee36b64bc4 100644 --- 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 @@ -10,6 +10,7 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import tools.jackson.databind.JsonNode; @@ -71,7 +72,7 @@ public record Deletion( 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; + if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java index e04093981e..20a9840c0f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -13,6 +13,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -35,63 +36,10 @@ public VersionAssetPublicationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "dsl"); } - /** - * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in - * this method are private Game Design owner keys and are not public identity aliases. - */ + /** Direct mapping writes cannot substitute for synchronized typed asset source ownership. */ public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { - requireTenantId(tenantId); - if (versionId <= 0 || assetId <= 0) { - throw new IllegalArgumentException("Version and asset owner keys must be positive"); - } - - VersionRow version = - lockVersionByTenantAndId(tenantId, versionId) - .orElseThrow(() -> new IllegalStateException("Exact tenant Version row was not found")); - qualifyVersion(version); - requireDraft(version); - requireNoSnapshot(tenantId, versionId); - - AssetRow asset = - findAssetForUpdate(tenantId, assetId) - .orElseThrow( - () -> new IllegalStateException("Exact tenant game asset row was not found")); - validateUsageKey(asset.fileName()); - - Record existing = - dsl.fetchOne( - "SELECT usage_key, usage_type FROM version_asset " - + "WHERE tenant_id = ? AND version_id = ? AND asset_id = ?", - tenantId, - versionId, - assetId); - if (existing != null) { - if (Objects.equals(existing.get("usage_key", String.class), asset.fileName()) - && Objects.equals(existing.get("usage_type", String.class), usageType)) { - return; - } - throw new IllegalStateException("Conflicting Version asset association already exists"); - } - - Record usageCollision = - dsl.fetchOne( - "SELECT asset_id FROM version_asset " - + "WHERE tenant_id = ? AND version_id = ? AND usage_key = ?", - tenantId, - versionId, - asset.fileName()); - if (usageCollision != null) { - throw new IllegalStateException("Version asset usage key is already mapped to another asset"); - } - - dsl.execute( - "INSERT INTO version_asset " - + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", - tenantId, - versionId, - assetId, - asset.fileName(), - usageType); + throw new IllegalStateException( + "Version asset associations require synchronized ASSET_REFERENCE source projection"); } /** @@ -112,6 +60,7 @@ public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { return readSnapshot(version); } requireDraft(version); + new AssetSourceRepository(dsl).requireExportSelection(tenantId, version.id()); List selected = lockMappedSourceAssets(tenantId, version.id()); selected.sort(Comparator.comparing(asset -> asset.usageKey(), UTF8_BYTE_ORDER)); @@ -456,28 +405,6 @@ private List lockMappedSourceAssets(String tenantId, long versionId row.get("byte_size", Long.class))); } - private Optional findAssetForUpdate(String tenantId, long assetId) { - Record row = - dsl.fetchOne( - "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", - tenantId, - assetId); - if (row == null) { - return Optional.empty(); - } - return Optional.of(new AssetRow(row.get("file_name", String.class))); - } - - private Optional lockVersionByTenantAndId(String tenantId, long versionId) { - return readVersion( - "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " - + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " - + "identity_source_game_tenant_key, identity_source_provenance_kind " - + "FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", - tenantId, - versionId); - } - private Optional lockVersionByTenantAndVersionNumber( String tenantId, int versionNumber) { return readVersion( @@ -575,13 +502,6 @@ private void requireDraft(VersionRow version) { } } - private void requireNoSnapshot(String tenantId, long versionId) { - if (hasSnapshot(tenantId, versionId)) { - throw new IllegalStateException( - "Version asset mappings are frozen by the durable export snapshot"); - } - } - private boolean hasSnapshot(String tenantId, long versionId) { return dsl.fetchOne( "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", @@ -669,8 +589,6 @@ private record VersionRow( String identitySourceGameTenantKey, String identitySourceProvenanceKind) {} - private record AssetRow(String fileName) {} - private record SourceAsset( String usageKey, Long assetId, diff --git a/services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql b/services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql new file mode 100644 index 0000000000..6771f1b0b2 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql @@ -0,0 +1,389 @@ +-- Ordinary source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_asset_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_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), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_asset_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + 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), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_asset_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + usage_key VARCHAR(255) NOT NULL, asset_id BIGINT, requiredness VARCHAR(16), + content_type VARCHAR(100), content_digest VARCHAR(71), byte_size BIGINT, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + 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, commit_id) + REFERENCES game_design_asset_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (asset_id) REFERENCES game_assets (id), + CHECK (usage_key !~ '^[[:space:]]*$' AND usage_key <> 'manifest.json'), + CHECK ((operation_kind = 'UPSERT' AND asset_id > 0 AND requiredness = 'REQUIRED' + AND content_type IS NOT NULL AND content_type !~ '^[[:space:]]*$' + AND content_digest ~ '^sha256:[0-9a-f]{64}$' AND byte_size >= 0) + OR (operation_kind = 'DELETE' AND asset_id IS NULL AND requiredness IS NULL + AND content_type IS NULL AND content_digest IS NULL AND byte_size IS NULL)) +); +CREATE TABLE game_design_asset_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, 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), + 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) +); +CREATE TABLE game_design_asset_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]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_asset_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_asset_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_asset_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_asset_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_asset_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), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + 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_asset_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION ordinary_asset_revision_item(r game_design_asset_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('family', 'ORDINARY', 'role', 'RESOURCE', 'usageKey', r.usage_key, + 'assetRowId', r.asset_id::TEXT, 'requiredness', r.requiredness, + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'contentType', r.content_type, 'contentDigest', r.content_digest, 'byteSize', r.byte_size::TEXT) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_ordinary_asset_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_asset_source_genesis%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_asset_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_asset_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + asset game_assets%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'ordinary asset source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'ordinary source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'ordinary genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_asset_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_asset_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'ordinary head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_asset_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'ordinary source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_head' 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.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'ordinary head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'ordinary staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'ordinary staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_asset_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 s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'ordinary visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'ordinary source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected 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 s FROM game_design_asset_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'ordinary capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c 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 TG_TABLE_NAME IN ('game_design_asset_source_revision', 'game_design_asset_source_application') THEN + IF NOT 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 AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'ordinary source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_revision' THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF (SELECT count(*) FROM json_object_keys((revision->>'payload')::JSON)) <> + (SELECT count(*) FROM jsonb_object_keys(payload)) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->>'revisionKind' IS DISTINCT FROM 'ASSET_REFERENCE' OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB + OR payload->>'family' IS DISTINCT FROM 'ORDINARY' OR payload->>'role' IS DISTINCT FROM 'RESOURCE' + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind OR payload->>'usageKey' IS DISTINCT FROM NEW.usage_key + OR jsonb_typeof(payload->'usageKey') IS DISTINCT FROM 'string' THEN RAISE EXCEPTION 'ordinary revision differs from exact payload' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'UPSERT' THEN + SELECT * INTO STRICT asset FROM game_assets WHERE id = NEW.asset_id AND tenant_id = v.tenant_id FOR UPDATE; + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 8 OR jsonb_typeof(payload->'assetRowId') IS DISTINCT FROM 'string' + OR payload->>'assetRowId' IS DISTINCT FROM NEW.asset_id::TEXT OR payload->>'requiredness' IS DISTINCT FROM 'REQUIRED' + OR NEW.requiredness IS DISTINCT FROM 'REQUIRED' OR asset.file_name IS DISTINCT FROM NEW.usage_key + OR asset.content_type IS DISTINCT FROM NEW.content_type OR asset.data IS NULL + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(asset.data), 'hex') OR NEW.byte_size IS DISTINCT FROM octet_length(asset.data)::BIGINT THEN + RAISE EXCEPTION 'ordinary RESOURCE requires exact required source bytes' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 6 THEN RAISE EXCEPTION 'ordinary DELETE fields invalid' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-ordinary-asset-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'items') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 7 THEN RAISE EXCEPTION 'ordinary snapshot binding invalid' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'items' INTO prior FROM game_design_asset_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_asset_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'ASSET_REFERENCE_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'ordinary application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT item->>'usageKey' AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.usage_key, r.revision_order, r.operation_kind = 'DELETE', ordinary_asset_revision_item(r) + FROM game_design_asset_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY convert_to(key, 'UTF8')) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'items' + OR (SELECT count(DISTINCT item->>'assetRowId') FROM jsonb_array_elements(expected_items) item) <> jsonb_array_length(expected_items) THEN + RAISE EXCEPTION 'ordinary application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'items' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility 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 AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'ordinary snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO policy_bytes 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; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE')) + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER ordinary_asset_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_genesis FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_head FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_revision FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_application FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_snapshot FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_capture FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE CONSTRAINT TRIGGER ordinary_asset_application_commit_guard AFTER INSERT ON game_design_asset_source_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_ordinary_asset_application_commit(); + +CREATE FUNCTION project_synchronized_ordinary_assets() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; item JSONB; +BEGIN + SELECT * INTO STRICT v FROM version WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + DELETE FROM version_asset WHERE tenant_id = v.tenant_id AND version_id = v.id; + FOR item IN SELECT * FROM jsonb_array_elements(NEW.snapshot_json::JSONB->'items') LOOP + INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key, usage_type) + VALUES (v.tenant_id, v.id, (item->>'assetRowId')::BIGINT, item->>'usageKey', NULL); + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_snapshot_projection AFTER INSERT ON game_design_asset_source_snapshot FOR EACH ROW EXECUTE FUNCTION project_synchronized_ordinary_assets(); + +CREATE FUNCTION require_ordinary_asset_projection() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; s game_design_asset_source_snapshot%ROWTYPE; tenant_key TEXT; version_key BIGINT; +BEGIN + tenant_key := CASE WHEN TG_OP = 'DELETE' THEN OLD.tenant_id ELSE NEW.tenant_id END; + version_key := CASE WHEN TG_OP = 'DELETE' THEN OLD.version_id ELSE NEW.version_id END; + SELECT * INTO STRICT v FROM version WHERE tenant_id = tenant_key AND id = version_key FOR UPDATE; + SELECT source.* INTO s FROM game_design_asset_source_snapshot source JOIN game_design_draft_commit_visibility f + USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE source.canonical_tenant_id = v.canonical_tenant_id AND source.canonical_version_id = v.canonical_version_id; + IF pg_trigger_depth() < 2 OR s.commit_id IS NULL OR TG_OP = 'UPDATE' + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection selected WHERE selected.canonical_tenant_id = v.canonical_tenant_id AND selected.canonical_version_id = v.canonical_version_id) + OR (TG_OP = 'INSERT' AND (NEW.usage_type IS NOT NULL OR NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'items') item WHERE item->>'assetRowId' = NEW.asset_id::TEXT AND item->>'usageKey' = NEW.usage_key))) THEN + RAISE EXCEPTION 'version_asset writes require exact synchronized ordinary source projection' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_mapping_projection_guard BEFORE INSERT OR UPDATE OR DELETE ON version_asset FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_projection(); + +CREATE FUNCTION require_ordinary_asset_export_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; s game_design_asset_source_snapshot%ROWTYPE; +BEGIN + SELECT * INTO STRICT v FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + SELECT source.* INTO STRICT s FROM game_design_asset_source_snapshot source + JOIN game_design_asset_source_head h USING (canonical_tenant_id, canonical_version_id) + JOIN game_design_draft_commit_visibility f USING (canonical_tenant_id, canonical_version_id) + WHERE source.canonical_tenant_id = v.canonical_tenant_id AND source.canonical_version_id = v.canonical_version_id + AND source.commit_id = h.visible_commit_id AND source.commit_id = f.commit_id + AND source.request_id = f.request_id + AND source.snapshot_json::JSONB->>'sourceEpoch' = h.source_epoch; + IF TG_TABLE_NAME = 'version_asset_export_snapshot' THEN + IF NEW.item_count <> jsonb_array_length(s.snapshot_json::JSONB->'items') THEN + RAISE EXCEPTION 'export requires exact synchronized ordinary source' USING ERRCODE = '23514'; END IF; + ELSIF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'items') item + WHERE item->>'usageKey' = NEW.usage_key AND item->>'assetRowId' = NEW.asset_id::TEXT + AND item->>'contentType' = NEW.content_type AND item->>'contentDigest' = NEW.content_hash + AND item->>'byteSize' = NEW.byte_size::TEXT) THEN + RAISE EXCEPTION 'export item differs from synchronized ordinary source' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_export_snapshot_source_guard BEFORE INSERT ON version_asset_export_snapshot FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_export_source(); +CREATE TRIGGER ordinary_asset_export_item_source_guard BEFORE INSERT ON version_asset_export_item FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_export_source(); + +CREATE FUNCTION protect_ordinary_asset_bytes() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_asset_source_revision r WHERE r.asset_id = OLD.id) AND + (TG_OP = 'DELETE' OR NEW IS DISTINCT FROM OLD) THEN + RAISE EXCEPTION 'ordinary asset source bytes are immutable from source history' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_byte_history_guard BEFORE UPDATE OR DELETE ON game_assets FOR EACH ROW EXECUTE FUNCTION protect_ordinary_asset_bytes(); + +CREATE FUNCTION deny_ordinary_asset_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'ordinary asset source history/projection cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_genesis_no_truncate BEFORE TRUNCATE ON game_design_asset_source_genesis EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_head_no_truncate BEFORE TRUNCATE ON game_design_asset_source_head EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_revision_no_truncate BEFORE TRUNCATE ON game_design_asset_source_revision EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_application_no_truncate BEFORE TRUNCATE ON game_design_asset_source_application EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_snapshot_no_truncate BEFORE TRUNCATE ON game_design_asset_source_snapshot EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_capture_no_truncate BEFORE TRUNCATE ON game_design_asset_source_capture EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_mapping_no_truncate BEFORE TRUNCATE ON version_asset EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_bytes_no_truncate BEFORE TRUNCATE ON game_assets EXECUTE FUNCTION deny_ordinary_asset_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1004__publication_operation_inventory_v2.sql b/services/game-design-service/src/main/resources/db/migration/V1004__publication_operation_inventory_v2.sql new file mode 100644 index 0000000000..db15cdbffc --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1004__publication_operation_inventory_v2.sql @@ -0,0 +1,291 @@ +-- Mandatory original World public inventory; retained operation/capture bytes are never rewritten. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selector JSONB; inventory JSONB; selected JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; i INTEGER; shape RECORD; member RECORD; + item JSONB; previous_key TEXT; counts INTEGER[] := ARRAY[]::INTEGER[]; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selected := convert_from(selected_inventory_operation_nth(input_bytes, 2), 'UTF8')::JSONB; + selector := convert_from(frames[3], 'UTF8')::JSONB; + IF NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Inventory requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + -- Closed public structure is mandatory even for direct SQL callers. This checks structure, + -- not producer authentication; GD cannot independently reconstruct World's private inputs. + FOR shape IN SELECT * FROM (VALUES + (inventory, ARRAY['schema','schemaVersion','completeness','ownerScope','selectedApplication','accountOrder','freeze','checkpoint','sourceModel','artifactDecisions']), + (owner, ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','intakeRequestDigest','sourceOperationId','sourceEvidenceDigest','intakeReceiptDigest']), + (application, ARRAY['applicationOperationId','applicationRequestId','appliedCommitId','bindingDigest','appliedResultDigest']), + (account_order, ARRAY['operationId','fenceId','actorAccountId','publicationRequestId','selectionDigest','selectedCommitId','bindingDigest']), + (frozen, ARRAY['publicationFence','publicationRequestId','requestDigest','versionStateEpoch','publishWorkflowId']), + (checkpoint, ARRAY['appliedCommitId','contentDigest','digestSchemaVersion']), + (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs']) + ) AS shapes(value, keys) LOOP + IF jsonb_typeof(shape.value) IS DISTINCT FROM 'object' + OR NOT shape.value ?& shape.keys + OR (SELECT count(*) FROM jsonb_object_keys(shape.value)) <> cardinality(shape.keys) + OR EXISTS (SELECT 1 FROM jsonb_each(shape.value) e WHERE e.value = 'null'::JSONB) THEN + RAISE EXCEPTION 'Incomplete or unknown public inventory members' USING ERRCODE = '23514'; END IF; + END LOOP; + FOR shape IN SELECT * FROM (VALUES (owner), (application), (account_order), (frozen), (checkpoint)) AS shapes(value) LOOP + FOR member IN SELECT * FROM jsonb_each(shape.value) LOOP + IF member.key <> 'digestSchemaVersion' AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Inventory binding members require exact string types' USING ERRCODE = '23514'; END IF; + IF member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND (member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000' THEN + RAISE EXCEPTION 'Canonical nonzero inventory UUID required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('intakeRequestDigest','sourceEvidenceDigest','intakeReceiptDigest','bindingDigest','appliedResultDigest','selectionDigest') + AND (member.value #>> '{}') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical inventory digest required' USING ERRCODE = '23514'; END IF; + END LOOP; + END LOOP; + IF owner->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' OR length(owner->>'targetNamespace') > 63 + OR frozen->>'versionStateEpoch' !~ '^[1-9][0-9]*$' OR (frozen->>'versionStateEpoch')::NUMERIC > 9223372036854775807 + OR frozen->>'requestDigest' !~ '^[0-9a-f]{64}$' OR checkpoint->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(checkpoint->'digestSchemaVersion') <> 'number' OR checkpoint->>'digestSchemaVersion' !~ '^[1-9][0-9]*$' + OR (checkpoint->>'digestSchemaVersion')::NUMERIC > 2147483647 + OR btrim(account_order->>'publicationRequestId') = '' OR btrim(account_order->>'publicationRequestId') <> account_order->>'publicationRequestId' + OR btrim(frozen->>'publicationRequestId') = '' OR btrim(frozen->>'publicationRequestId') <> frozen->>'publicationRequestId' + OR btrim(frozen->>'publishWorkflowId') = '' OR btrim(frozen->>'publishWorkflowId') <> frozen->>'publishWorkflowId' + OR model->>'graphDigest' !~ '^sha256:[0-9a-f]{64}$' OR model->>'topologyResultDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(model->'modelId') <> 'string' OR jsonb_typeof(model->'graphDigest') <> 'string' + OR jsonb_typeof(model->'topologyResultDigest') <> 'string' + OR model->'generationRuleFields' <> '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' <> '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' <> '["id","regionId","name"]'::JSONB + OR model->'roomFields' <> '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' <> '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' <> '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR jsonb_typeof(model->'familyCounts') <> 'array' OR jsonb_array_length(model->'familyCounts') <> 6 + OR jsonb_typeof(model->'regionGeneratorInputs') <> 'array' OR jsonb_typeof(model->'spawnBindingInputs') <> 'array' + OR jsonb_typeof(model->'spawnBindingCount') <> 'number' OR model->>'spawnBindingCount' !~ '^(0|[1-9][0-9]*)$' + OR (model->>'spawnBindingCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Unsupported public inventory source profile' USING ERRCODE = '23514'; END IF; + FOR i IN 0..5 LOOP + item := model->'familyCounts'->i; + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['family','rowCount'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 2 + OR item->'family' IS DISTINCT FROM to_jsonb((ARRAY['REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING'])[i+1]) + OR jsonb_typeof(item->'rowCount') IS DISTINCT FROM 'number' OR item->>'rowCount' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'rowCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Incomplete source family enumeration' USING ERRCODE = '23514'; END IF; + counts := array_append(counts, (item->>'rowCount')::INTEGER); + END LOOP; + IF counts[3] < 1 OR counts[5] <> 0 OR counts[1] <> jsonb_array_length(model->'regionGeneratorInputs') + OR counts[6] <> jsonb_array_length(model->'spawnBindingInputs') OR counts[6] <> (model->>'spawnBindingCount')::INTEGER THEN + RAISE EXCEPTION 'Source inventory counts differ from explicit inputs' USING ERRCODE = '23514'; END IF; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'regionGeneratorInputs') LOOP + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['regionTemplateId','generatorType','generatorParams'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 3 + OR jsonb_typeof(item->'regionTemplateId') IS DISTINCT FROM 'string' + OR item->>'regionTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR item->>'regionTemplateId' = '00000000-0000-0000-0000-000000000000' + OR previous_key COLLATE "C" >= (item->>'regionTemplateId') COLLATE "C" + OR item->'generatorType' IS DISTINCT FROM '""'::JSONB OR item->'generatorParams' IS DISTINCT FROM '""'::JSONB THEN + RAISE EXCEPTION 'Unsupported or unordered region generator input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'regionTemplateId'; + END LOOP; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'spawnBindingInputs') LOOP + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['bindingTemplateId','roomTemplateId','entityTemplateType','entityReferenceKind','entityTenantId','entityVersionId','entityTemplateId','spawnCount','respawnDelaySeconds'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 9 THEN + RAISE EXCEPTION 'Incomplete spawn input' USING ERRCODE = '23514'; END IF; + FOR member IN SELECT * FROM jsonb_each(item) LOOP + IF member.key NOT IN ('spawnCount','respawnDelaySeconds') AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Spawn reference exact string required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('bindingTemplateId','roomTemplateId','entityTenantId','entityVersionId','entityTemplateId') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical spawn UUID required' USING ERRCODE = '23514'; END IF; + END LOOP; + IF item->>'entityReferenceKind' <> 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR item->>'entityTenantId' <> owner->>'canonicalTenantId' OR item->>'entityVersionId' <> owner->>'canonicalVersionId' + OR item->>'entityTemplateType' NOT IN ('ITEM','NPC') + OR jsonb_typeof(item->'spawnCount') IS DISTINCT FROM 'number' OR item->>'spawnCount' !~ '^[1-9][0-9]*$' + OR (item->>'spawnCount')::NUMERIC > 2147483647 + OR jsonb_typeof(item->'respawnDelaySeconds') IS DISTINCT FROM 'number' OR item->>'respawnDelaySeconds' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'respawnDelaySeconds')::NUMERIC > 2147483647 + OR previous_key COLLATE "C" >= (item->>'bindingTemplateId') COLLATE "C" THEN + RAISE EXCEPTION 'Unsupported or unordered scoped spawn input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'bindingTemplateId'; + END LOOP; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements((selected->>'selectedCommitBindingJson')::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE 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; + PERFORM require_selected_inventory_operation_v2(NEW.request_bytes); + 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/v2' + 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; +-- [jooq ignore stop] + +-- A retained v1 operation stays immutable, but cannot acquire a new source capture. +-- [jooq ignore start] +CREATE FUNCTION guard_selected_inventory_capture_v2() RETURNS trigger AS $$ +BEGIN + PERFORM require_selected_inventory_operation_v2(NEW.operation_bytes); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER command_capture_inventory_v2 BEFORE INSERT ON game_design_command_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); +CREATE TRIGGER policy_capture_inventory_v2 BEFORE INSERT ON game_design_realm_policy_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); +CREATE TRIGGER asset_capture_inventory_v2 BEFORE INSERT ON game_design_asset_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); + +-- Historical v1 publication bytes remain readable history, never new derived policy authority. +-- Run before the original policy-set guard; all of its lifecycle/immutability checks still run +-- for a structurally valid v2 operation, including the one permitted sealing UPDATE. +CREATE FUNCTION guard_published_policy_inventory_v2() RETURNS trigger AS $$ +BEGIN + IF selected_inventory_operation_nth(NEW.operation_bytes, 0) + IS DISTINCT FROM convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'Published realm policy evidence requires immutable v2 operation' + USING ERRCODE = '23514'; + END IF; + PERFORM require_selected_inventory_operation_v2(NEW.operation_bytes); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER a_published_policy_inventory_v2 BEFORE INSERT OR UPDATE + ON game_design_published_realm_policy_set + FOR EACH ROW EXECUTE FUNCTION guard_published_policy_inventory_v2(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1005__gameplay_rule_source.sql b/services/game-design-service/src/main/resources/db/migration/V1005__gameplay_rule_source.sql new file mode 100644 index 0000000000..fa170cf253 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1005__gameplay_rule_source.sql @@ -0,0 +1,400 @@ +-- Authored gameplay-rule inventory. No retained Draft receives an inferred empty baseline. +CREATE TABLE game_design_gameplay_rule_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, inventory_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), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_gameplay_rule_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + 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), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_gameplay_rule_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + family VARCHAR(64) NOT NULL, definition_key VARCHAR(128) NOT NULL, payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + 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, commit_id) + REFERENCES game_design_gameplay_rule_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_kind IN ('UPSERT', 'DELETE')), + CHECK (definition_key ~ '^[A-Za-z][A-Za-z0-9_.:-]{0,127}$') +); +CREATE TABLE game_design_gameplay_rule_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, 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), + 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) +); +CREATE TABLE game_design_gameplay_rule_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]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_gameplay_rule_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_gameplay_rule_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_gameplay_rule_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_gameplay_rule_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION gameplay_rule_families() RETURNS TEXT[] AS $$ + SELECT ARRAY['STATS', 'RESOURCES', 'CONDITIONS', 'EFFECTS', 'ABILITIES', 'ACTIONS', 'COMMANDS', + 'ADMISSION_TAGS', 'DISPOSITIONS', 'CONTINUOUS_OVERLAYS', 'OBSERVATION_POLICIES', + 'TARGETING_POLICIES', 'SELECTION_POLICIES', 'DEFAULT_BINDINGS', 'FEEDBACK']::TEXT[]; +$$ LANGUAGE SQL IMMUTABLE; + +CREATE FUNCTION gameplay_rule_definition_key(family TEXT, definition JSONB) RETURNS TEXT AS $$ + SELECT CASE family WHEN 'ABILITIES' THEN definition->>'abilityId' + WHEN 'ACTIONS' THEN definition->>'actionSequenceId' + WHEN 'STATS' THEN definition->>'statKey' WHEN 'RESOURCES' THEN definition->>'statKey' + WHEN 'CONDITIONS' THEN definition->>'conditionKey' WHEN 'EFFECTS' THEN definition->>'effectKey' + WHEN 'COMMANDS' THEN definition->>'commandId' WHEN 'ADMISSION_TAGS' THEN definition->>'tagKey' + WHEN 'DISPOSITIONS' THEN definition->>'dispositionKey' WHEN 'CONTINUOUS_OVERLAYS' THEN definition->>'overlayKey' + WHEN 'OBSERVATION_POLICIES' THEN definition->>'observationPolicyKey' + WHEN 'TARGETING_POLICIES' THEN definition->>'targetingPolicyKey' + WHEN 'SELECTION_POLICIES' THEN definition->>'targetSelectionPolicyKey' + WHEN 'DEFAULT_BINDINGS' THEN definition->>'bindingKey' WHEN 'FEEDBACK' THEN definition->>'feedbackKey' ELSE NULL END; +$$ LANGUAGE SQL IMMUTABLE; + +CREATE FUNCTION guard_gameplay_rule_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_gameplay_rule_genesis%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_gameplay_rule_application%ROWTYPE; s game_design_gameplay_rule_snapshot%ROWTYPE; + revision JSONB; payload JSONB; snapshot JSONB; prior JSONB; manifest JSONB; + expected_entries JSONB; replacement JSONB; r game_design_gameplay_rule_revision%ROWTYPE; + family TEXT; family_values JSONB; present BOOLEAN; actual_count BIGINT; declared_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'gameplay source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game source + ON source.id = owner.identity_source_game_row_id AND source.tenant_id = owner.identity_source_game_tenant_key + AND source.tenant_id = owner.tenant_id AND source.canonical_tenant_id = owner.canonical_tenant_id + AND source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND source.tenant_identity_source_game_id = source.id AND source.tenant_identity_source_legacy_tenant_id = source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'gameplay source requires exact canonical full Draft' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_genesis' THEN + manifest := NEW.inventory_json::JSONB; + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w + WHERE w.version_id = v.id AND w.creation_transaction_id = NEW.creation_transaction_id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit old_commit WHERE old_commit.canonical_tenant_id = NEW.canonical_tenant_id + AND old_commit.canonical_version_id = NEW.canonical_version_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object('canonicalTenantId', v.canonical_tenant_id::TEXT, + 'canonicalVersionId', v.canonical_version_id::TEXT, 'gameDesignVersionRowId', v.id, + 'gameDesignVersionTenantKey', v.tenant_id, 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR manifest->>'schema' IS DISTINCT FROM 'gameplay-rule-manifest/v1' + OR (SELECT count(*) FROM jsonb_object_keys(manifest)) <> 2 + OR (SELECT count(*) FROM jsonb_object_keys(manifest->'families')) <> cardinality(gameplay_rule_families()) THEN + RAISE EXCEPTION 'gameplay genesis requires actual fresh complete owner inventory' USING ERRCODE = '23514'; END IF; + FOREACH family IN ARRAY gameplay_rule_families() LOOP + IF manifest->'families'->family IS DISTINCT FROM '[]'::JSONB THEN + RAISE EXCEPTION 'every fresh gameplay family must be explicitly empty' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_gameplay_rule_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL + OR NEW.genesis_receipt_id <> g.receipt_id THEN RAISE EXCEPTION 'gameplay head requires exact fresh genesis' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection p WHERE p.canonical_tenant_id = NEW.canonical_tenant_id + AND p.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'selected gameplay source is frozen' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_head' 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.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN RAISE EXCEPTION 'gameplay head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'gameplay epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'gameplay application pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_gameplay_rule_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 s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'gameplay visibility pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'gameplay source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT * INTO STRICT c 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 TG_TABLE_NAME = 'game_design_gameplay_rule_revision' THEN + SELECT x INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'revisionId' = NEW.revision_id::TEXT + AND (x->>'revisionOrder')::INTEGER = NEW.revision_order; + payload := (revision->>'payload')::JSONB; + IF payload IS DISTINCT FROM NEW.payload_json::JSONB OR payload->>'revisionKind' IS DISTINCT FROM 'GAMEPLAY_RULE' + OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR payload->>'family' IS DISTINCT FROM NEW.family OR NOT NEW.family = ANY(gameplay_rule_families()) + OR (NEW.operation_kind = 'UPSERT' AND (gameplay_rule_definition_key(NEW.family, (payload->>'definitionJson')::JSONB) IS DISTINCT FROM NEW.definition_key + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5)) + OR (NEW.operation_kind = 'DELETE' AND (payload->>'key' IS DISTINCT FROM NEW.definition_key + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5)) THEN + RAISE EXCEPTION 'gameplay revision differs from original complete binding' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-gameplay-rule-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN + RAISE EXCEPTION 'gameplay snapshot exact binding missing' USING ERRCODE = '23514'; END IF; + SELECT old_snapshot.snapshot_json::JSONB->'entries' INTO prior FROM game_design_gameplay_rule_snapshot old_snapshot + WHERE old_snapshot.canonical_tenant_id = NEW.canonical_tenant_id AND old_snapshot.canonical_version_id = NEW.canonical_version_id + AND old_snapshot.commit_id = h.visible_commit_id; + IF h.visible_commit_id IS NOT NULL AND prior IS NULL THEN RAISE EXCEPTION 'gameplay predecessor unavailable' USING ERRCODE = '23514'; END IF; + expected_entries := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_gameplay_rule_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT 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 AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'GAMEPLAY_RULE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'GAMEPLAY_RULE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'gameplay application scope epoch mismatch' USING ERRCODE = '23514'; END IF; + FOR r IN SELECT * FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id ORDER BY revision_order LOOP + SELECT EXISTS (SELECT 1 FROM jsonb_array_elements(expected_entries) item WHERE item->>'family' = r.family + AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key) INTO present; + IF r.operation_kind = 'DELETE' THEN + IF NOT present THEN RAISE EXCEPTION 'gameplay DELETE requires existing key' USING ERRCODE = '23514'; END IF; + SELECT coalesce(jsonb_agg(item ORDER BY ordinal), '[]'::JSONB) INTO expected_entries + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal) + WHERE NOT (item->>'family' = r.family AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key); + ELSE + replacement := jsonb_build_object('family', r.family, 'definitionJson', r.payload_json::JSONB->>'definitionJson', + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT); + IF present THEN + SELECT jsonb_agg(CASE WHEN item->>'family' = r.family AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key + THEN replacement ELSE item END ORDER BY ordinal) INTO expected_entries + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal); + ELSE expected_entries := expected_entries || jsonb_build_array(replacement); END IF; + END IF; + END LOOP; + SELECT coalesce(jsonb_agg(item ORDER BY array_position(gameplay_rule_families(), item->>'family'), ordinal), '[]'::JSONB) + INTO expected_entries FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal); + ELSE + SELECT * INTO a FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO declared_count FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + IF (declared_count > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND NEW.snapshot_json IS DISTINCT FROM a.snapshot_json) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility visible WHERE visible.canonical_tenant_id = NEW.canonical_tenant_id + AND visible.canonical_version_id = NEW.canonical_version_id AND visible.request_id = NEW.request_id + AND visible.commit_id = NEW.commit_id AND visible.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'gameplay snapshot lacks synchronized complete owner source' USING ERRCODE = '23514'; END IF; + IF a.commit_id IS NOT NULL THEN expected_entries := a.snapshot_json::JSONB->'entries'; END IF; + END IF; + IF snapshot->'entries' IS DISTINCT FROM expected_entries THEN RAISE EXCEPTION 'gameplay snapshot must replay exact original revisions' USING ERRCODE = '23514'; END IF; + manifest := (snapshot->>'manifestJson')::JSONB; + IF manifest->>'schema' IS DISTINCT FROM 'gameplay-rule-manifest/v1' + OR (SELECT count(*) FROM jsonb_object_keys(manifest)) <> 2 + OR (SELECT count(*) FROM jsonb_object_keys(manifest->'families')) <> cardinality(gameplay_rule_families()) THEN + RAISE EXCEPTION 'gameplay snapshot inventory is incomplete' USING ERRCODE = '23514'; END IF; + FOREACH family IN ARRAY gameplay_rule_families() LOOP + SELECT coalesce(jsonb_agg((item->>'definitionJson')::JSONB ORDER BY ordinal), '[]'::JSONB) INTO family_values + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal) WHERE item->>'family' = family; + IF manifest->'families'->family IS DISTINCT FROM family_values THEN + RAISE EXCEPTION 'gameplay manifest differs from its complete original source' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gameplay_rule_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_genesis FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_head FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_revision FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_application FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_snapshot FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE CONSTRAINT TRIGGER gameplay_rule_application_commit_guard AFTER INSERT ON game_design_gameplay_rule_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_gameplay_rule_application_commit(); +CREATE FUNCTION deny_gameplay_rule_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'gameplay source history cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gameplay_rule_genesis_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_genesis EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_head_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_head EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_revision_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_revision EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_application_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_application EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_snapshot_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_snapshot EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO policy_bytes 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; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE')) + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1006__draft_application_lifecycle_interlock.sql b/services/game-design-service/src/main/resources/db/migration/V1006__draft_application_lifecycle_interlock.sql new file mode 100644 index 0000000000..52e038eb63 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1006__draft_application_lifecycle_interlock.sql @@ -0,0 +1,124 @@ +-- An admitted original source operation must remain locally completable or definitively abortable +-- while Account ordering runs outside SQL. Publication selection has its existing V43 interlock. +-- [jooq ignore start] +-- Keep retained-state preflight and guard installation atomic against both writer directions. +LOCK TABLE version IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE game_design_draft_commit_application_slot IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE game_design_authored_draft_publish_selection IN SHARE ROW EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_design_draft_commit_application_slot s + LEFT JOIN game_design_draft_commit c + ON c.canonical_tenant_id = s.canonical_tenant_id + AND c.canonical_version_id = s.canonical_version_id + AND c.request_id = s.request_id AND c.commit_id = s.commit_id + LEFT JOIN version v + ON v.id = c.game_design_version_row_id + AND v.tenant_id = c.game_design_version_tenant_key + AND v.canonical_tenant_id = c.canonical_tenant_id + AND v.canonical_version_id = c.canonical_version_id + AND v.identity_source_game_row_id = c.source_game_row_id + AND v.identity_source_game_tenant_key = c.source_game_tenant_key + AND v.identity_source_provenance_kind = c.source_provenance_kind + WHERE v.id IS NULL OR v.version_state IS DISTINCT FROM 'DRAFT' + ) THEN + RAISE EXCEPTION 'Retained Draft application slot lacks its exact DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot slot + JOIN game_design_authored_draft_publish_selection selection + USING (canonical_tenant_id, canonical_version_id) + ) THEN + RAISE EXCEPTION 'Retained Draft application slot conflicts with authored publication selection' + USING ERRCODE = 'check_violation'; + END IF; +END; +$$; + +CREATE FUNCTION reject_gd_version_lifecycle_during_draft_application() RETURNS trigger AS $$ +BEGIN + IF NEW.version_state IS NOT DISTINCT FROM OLD.version_state + AND NEW.version_state_epoch IS NOT DISTINCT FROM OLD.version_state_epoch THEN + RETURN NEW; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = OLD.canonical_tenant_id + AND s.canonical_version_id = OLD.canonical_version_id + ) THEN + RAISE EXCEPTION 'Active or unresolved Draft application prevents Version lifecycle changes' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_version_draft_application_lifecycle_interlock + BEFORE UPDATE OF version_state, version_state_epoch ON version + FOR EACH ROW + EXECUTE FUNCTION reject_gd_version_lifecycle_during_draft_application(); + +CREATE FUNCTION serialize_gd_draft_application_version() RETURNS trigger AS $$ +BEGIN + -- Acquire the Version write lock before V42's parent-commit lock or any slot lock. A physical + -- no-logical-change UPDATE creates an MVCC conflict for stale REPEATABLE READ/SERIALIZABLE + -- lifecycle writers; a row lock alone would let their old snapshot miss a committed slot. + -- All Version fields, including epoch, timestamps and history, retain their exact values. + UPDATE version v SET version_state = v.version_state + 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.request_id AND c.commit_id = NEW.commit_id + AND v.id = c.game_design_version_row_id + AND v.tenant_id = c.game_design_version_tenant_key + AND v.canonical_tenant_id = c.canonical_tenant_id + AND v.canonical_version_id = c.canonical_version_id + AND v.identity_source_game_row_id = c.source_game_row_id + AND v.identity_source_game_tenant_key = c.source_game_tenant_key + AND v.identity_source_provenance_kind = c.source_provenance_kind + AND v.version_state = 'DRAFT'; + IF NOT FOUND THEN + RAISE EXCEPTION 'Draft application slot requires its exact current DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- PostgreSQL runs same-kind triggers by name: this must precede both retained V42/V43 guards. +CREATE TRIGGER a_gd_draft_application_version_interlock + BEFORE INSERT ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION serialize_gd_draft_application_version(); + +CREATE FUNCTION serialize_gd_authored_selection_version() RETURNS trigger AS $$ +BEGIN + -- The reverse publication ordering needs the same MVCC serialization: merely locking Version + -- in V43 leaves a stale slot inserter's snapshot unaware of a newly committed selection. + UPDATE version v SET version_state = v.version_state + 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; + IF NOT FOUND THEN + RAISE EXCEPTION 'Authored Draft selection requires its exact current DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER a_gd_authored_selection_version_interlock + BEFORE INSERT ON game_design_authored_draft_publish_selection + FOR EACH ROW + EXECUTE FUNCTION serialize_gd_authored_selection_version(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql b/services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql new file mode 100644 index 0000000000..298efd4b32 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql @@ -0,0 +1,495 @@ +-- Branding source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_branding_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, roles_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), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_branding_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + 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), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_branding_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + usage_key VARCHAR(255) NOT NULL, role VARCHAR(16) NOT NULL CHECK (role IN ('RESOURCE', 'LOGO', 'FAVICON', 'THEME')), asset_id BIGINT, requiredness VARCHAR(16), + content_type VARCHAR(100), content_digest VARCHAR(71), byte_size BIGINT, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + 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, commit_id) + REFERENCES game_design_branding_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (asset_id) REFERENCES game_assets (id), + CHECK (usage_key !~ '^[[:space:]]*$' AND usage_key <> 'manifest.json'), + CHECK ((operation_kind = 'UPSERT' AND asset_id > 0 AND requiredness = 'REQUIRED' + AND content_type IS NOT NULL AND content_type !~ '^[[:space:]]*$' + AND content_digest ~ '^sha256:[0-9a-f]{64}$' AND byte_size >= 0) + OR (operation_kind = 'DELETE' AND asset_id IS NULL AND requiredness IS NULL + AND content_type IS NULL AND content_digest IS NULL AND byte_size IS NULL)) +); +CREATE TABLE game_design_branding_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, 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), + 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) +); +CREATE TABLE game_design_branding_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]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_branding_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_branding_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_branding_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_branding_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_branding_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), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + 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_branding_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION branding_asset_revision_item(r game_design_branding_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('family', 'BRANDING', 'role', r.role, 'usageKey', r.usage_key, + 'assetRowId', r.asset_id::TEXT, 'requiredness', r.requiredness, + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'contentType', r.content_type, 'contentDigest', r.content_digest, 'byteSize', r.byte_size::TEXT) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_branding_asset_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_branding_source_genesis%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_branding_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_branding_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + asset game_assets%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'branding asset source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'branding source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.roles_json::JSONB IS DISTINCT FROM '{"RESOURCE":"EMPTY","LOGO":"EMPTY","FAVICON":"EMPTY","THEME":"EMPTY"}'::JSONB + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'branding genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_branding_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_branding_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'branding head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_branding_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'branding source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_head' 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.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'branding head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'branding staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'branding staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_branding_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 s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'branding visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'branding source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected 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 s FROM game_design_branding_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'branding capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c 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 TG_TABLE_NAME IN ('game_design_branding_source_revision', 'game_design_branding_source_application') THEN + IF NOT 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 AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'branding source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_revision' THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF (SELECT count(*) FROM json_object_keys((revision->>'payload')::JSON)) <> + (SELECT count(*) FROM jsonb_object_keys(payload)) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->>'revisionKind' IS DISTINCT FROM 'BRANDING_ASSET_REFERENCE' OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB + OR payload->>'family' IS DISTINCT FROM 'BRANDING' OR payload->>'role' IS DISTINCT FROM NEW.role + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind OR payload->>'usageKey' IS DISTINCT FROM NEW.usage_key + OR jsonb_typeof(payload->'usageKey') IS DISTINCT FROM 'string' THEN RAISE EXCEPTION 'branding revision differs from exact payload' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'UPSERT' THEN + SELECT * INTO STRICT asset FROM game_assets WHERE id = NEW.asset_id AND tenant_id = v.tenant_id FOR UPDATE; + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 8 OR jsonb_typeof(payload->'assetRowId') IS DISTINCT FROM 'string' + OR payload->>'assetRowId' IS DISTINCT FROM NEW.asset_id::TEXT OR payload->>'requiredness' IS DISTINCT FROM 'REQUIRED' + OR NEW.requiredness IS DISTINCT FROM 'REQUIRED' OR asset.file_name IS DISTINCT FROM NEW.usage_key + OR asset.content_type IS DISTINCT FROM NEW.content_type OR asset.data IS NULL + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(asset.data), 'hex') OR NEW.byte_size IS DISTINCT FROM octet_length(asset.data)::BIGINT THEN + RAISE EXCEPTION 'branding RESOURCE requires exact required source bytes' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 6 THEN RAISE EXCEPTION 'branding DELETE fields invalid' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-branding-asset-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'items') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN RAISE EXCEPTION 'branding snapshot binding invalid' USING ERRCODE = '23514'; END IF; + IF snapshot->'roles' IS DISTINCT FROM ( + SELECT jsonb_object_agg(role, CASE WHEN EXISTS ( + SELECT 1 FROM jsonb_array_elements(snapshot->'items') item WHERE item->>'role' = role + ) THEN 'PRESENT' ELSE 'EMPTY' END) + FROM unnest(ARRAY['RESOURCE', 'LOGO', 'FAVICON', 'THEME']) role + ) THEN RAISE EXCEPTION 'branding snapshot requires every explicit role declaration' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'items' INTO prior FROM game_design_branding_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_branding_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'BRANDING_ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'BRANDING_ASSET_REFERENCE_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'branding application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT item->>'usageKey' AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.usage_key, r.revision_order, r.operation_kind = 'DELETE', branding_asset_revision_item(r) + FROM game_design_branding_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY convert_to(key, 'UTF8')) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'items' + OR (SELECT count(DISTINCT item->>'assetRowId') FROM jsonb_array_elements(expected_items) item) <> jsonb_array_length(expected_items) THEN + RAISE EXCEPTION 'branding application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'items' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility 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 AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'branding snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_branding_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_branding_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + branding_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; branding_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c 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 r 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 h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + SELECT result_bytes INTO policy_bytes 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; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE', 'BRANDING_ASSET_REFERENCE')) + OR (branding_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE') + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN branding_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER branding_asset_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_genesis FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_head FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_revision FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_application FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_snapshot FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_capture FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE CONSTRAINT TRIGGER branding_asset_application_commit_guard AFTER INSERT ON game_design_branding_source_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_branding_asset_application_commit(); +CREATE FUNCTION protect_branding_asset_bytes() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_branding_source_revision r WHERE r.asset_id = OLD.id) AND + (TG_OP = 'DELETE' OR NEW IS DISTINCT FROM OLD) THEN + RAISE EXCEPTION 'branding asset source bytes are immutable from source history' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER branding_asset_byte_history_guard BEFORE UPDATE OR DELETE ON game_assets FOR EACH ROW EXECUTE FUNCTION protect_branding_asset_bytes(); + +CREATE FUNCTION deny_branding_asset_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'branding source history cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER branding_asset_genesis_no_truncate BEFORE TRUNCATE ON game_design_branding_source_genesis EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_head_no_truncate BEFORE TRUNCATE ON game_design_branding_source_head EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_revision_no_truncate BEFORE TRUNCATE ON game_design_branding_source_revision EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_application_no_truncate BEFORE TRUNCATE ON game_design_branding_source_application EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_snapshot_no_truncate BEFORE TRUNCATE ON game_design_branding_source_snapshot EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_capture_no_truncate BEFORE TRUNCATE ON game_design_branding_source_capture EXECUTE FUNCTION deny_branding_asset_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1008__template_config_source_history.sql b/services/game-design-service/src/main/resources/db/migration/V1008__template_config_source_history.sql new file mode 100644 index 0000000000..e9a2e29735 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1008__template_config_source_history.sql @@ -0,0 +1,870 @@ +-- Template/config authored source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_template_config_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_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), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_template_config_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + 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), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_template_config_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + template_id BIGINT NOT NULL REFERENCES game_templates (id), payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + 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, commit_id) + REFERENCES game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_kind IN ('CREATE', 'UPSERT', 'DELETE')) +); +CREATE TABLE game_design_template_config_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, 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), + 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) +); +CREATE TABLE game_design_template_config_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]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_template_config_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_template_config_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), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + 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_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +CREATE TABLE game_design_template_config_source_qualification ( + template_id BIGINT PRIMARY KEY REFERENCES game_templates (id), + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, revision_order INTEGER NOT NULL, + UNIQUE (canonical_tenant_id, canonical_version_id, revision_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, revision_id) + REFERENCES game_design_template_config_source_revision (canonical_tenant_id, canonical_version_id, revision_id) + DEFERRABLE INITIALLY DEFERRED +); +CREATE TABLE game_design_template_config_source_ref ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, revision_id UUID NOT NULL, + ref_kind VARCHAR(64) NOT NULL, ref_key VARCHAR(128) NOT NULL, referenced_revision_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, revision_id) + REFERENCES game_design_template_config_source_revision (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, referenced_revision_id) + REFERENCES game_design_gameplay_rule_revision (canonical_tenant_id, canonical_version_id, revision_id), + CHECK ((ref_kind = 'BASE_VERSION' AND referenced_revision_id IS NULL AND ref_key = canonical_version_id::TEXT) + OR (ref_kind <> 'BASE_VERSION' AND referenced_revision_id IS NOT NULL)) +); +CREATE TABLE game_design_template_config_source_row_insert ( + template_id BIGINT PRIMARY KEY, creation_transaction_id TEXT NOT NULL +); +-- [jooq ignore start] +CREATE FUNCTION template_config_unique_json(value JSON) RETURNS BOOLEAN AS $$ +DECLARE field RECORD; element JSON; +BEGIN + IF json_typeof(value) = 'object' THEN + IF (SELECT count(*) FROM json_each(value)) <> (SELECT count(DISTINCT key) FROM json_each(value)) THEN RETURN FALSE; END IF; + FOR field IN SELECT * FROM json_each(value) LOOP + IF NOT template_config_unique_json(field.value) THEN RETURN FALSE; END IF; + END LOOP; + ELSIF json_typeof(value) = 'array' THEN + FOR element IN SELECT * FROM json_array_elements(value) LOOP + IF NOT template_config_unique_json(element) THEN RETURN FALSE; END IF; + END LOOP; + END IF; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION template_config_supported(config_json TEXT, base_id UUID) RETURNS BOOLEAN AS $$ +DECLARE cfg JSONB := config_json::JSONB; input JSONB; +BEGIN + IF NOT template_config_unique_json(config_json::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(cfg)) <> 7 + OR config_json::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR cfg->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR cfg->>'baseVersionId' IS DISTINCT FROM base_id::TEXT + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'world')) <> 2 + OR cfg->'world'->'regions' IS DISTINCT FROM '[]'::JSONB OR cfg->'world'->'rooms' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'entity')) <> 2 + OR cfg->'entity'->'items' IS DISTINCT FROM '[]'::JSONB OR cfg->'entity'->'npcs' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'automation')) <> 2 + OR cfg->'automation'->'scripts' IS DISTINCT FROM '[]'::JSONB + OR cfg->'automation'->'scriptPatch' IS DISTINCT FROM '{"presence":"ABSENT"}'::JSONB + OR cfg->'supportedSettings' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'gameLogic')) <> 1 + OR jsonb_typeof(cfg->'gameLogic'->'inputs') IS DISTINCT FROM 'array' THEN RETURN FALSE; END IF; + FOR input IN SELECT * FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') LOOP + IF (SELECT count(*) FROM jsonb_object_keys(input)) <> 3 + OR NOT (input->>'family' = ANY(gameplay_rule_families())) + OR jsonb_typeof(input->'family') IS DISTINCT FROM 'string' + OR jsonb_typeof(input->'key') IS DISTINCT FROM 'string' + OR (input->>'key') !~ '^[A-Za-z][A-Za-z0-9_.:-]{0,127}$' + OR jsonb_typeof(input->'revisionId') IS DISTINCT FROM 'string' + OR input->>'revisionId' IS DISTINCT FROM ((input->>'revisionId')::UUID)::TEXT + OR (input->>'revisionId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID THEN RETURN FALSE; END IF; + END LOOP; + RETURN (SELECT count(*) FROM jsonb_array_elements(cfg->'gameLogic'->'inputs')) = + (SELECT count(DISTINCT (x->>'family', x->>'key')) FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') x); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION template_config_revision_item(r game_design_template_config_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('templateId', r.template_id::TEXT, 'configJson', r.payload_json::JSONB->>'configJson', + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'createdName', CASE WHEN r.operation_kind = 'CREATE' THEN r.payload_json::JSONB->>'templateName' ELSE '' END) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION template_config_selected_inputs(snapshot JSONB, p_tenant UUID, p_version UUID, p_commit UUID) RETURNS BOOLEAN AS $$ +DECLARE gameplay game_design_gameplay_rule_snapshot%ROWTYPE; entry JSONB; input JSONB; +BEGIN + SELECT * INTO STRICT gameplay FROM game_design_gameplay_rule_snapshot WHERE canonical_tenant_id = p_tenant + AND canonical_version_id = p_version AND commit_id = p_commit; + IF gameplay.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM snapshot->>'bindingJson' THEN RETURN FALSE; END IF; + FOR entry IN SELECT * FROM jsonb_array_elements(snapshot->'entries') LOOP + FOR input IN SELECT * FROM jsonb_array_elements((entry->>'configJson')::JSONB->'gameLogic'->'inputs') LOOP + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(gameplay.snapshot_json::JSONB->'entries') e + WHERE e->>'family' = input->>'family' AND e->>'revisionId' = input->>'revisionId' + AND gameplay_rule_definition_key(e->>'family', (e->>'definitionJson')::JSONB) = input->>'key') THEN RETURN FALSE; END IF; + END LOOP; + END LOOP; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql STABLE; +CREATE FUNCTION template_config_current_inventory(p_tenant UUID, p_version UUID, p_private_version BIGINT, + p_legacy_tenant TEXT, snapshot JSONB) RETURNS BOOLEAN AS $$ + SELECT NOT EXISTS ( + SELECT 1 FROM game_templates t + LEFT JOIN game_design_template_config_source_qualification q ON q.template_id = t.id + AND q.canonical_tenant_id = p_tenant AND q.canonical_version_id = p_version + LEFT JOIN LATERAL ( + SELECT r.operation_kind FROM game_design_template_config_source_revision r + JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = r.canonical_tenant_id + AND a.canonical_version_id = r.canonical_version_id AND a.commit_id = r.commit_id + WHERE r.canonical_tenant_id = p_tenant AND r.canonical_version_id = p_version AND r.template_id = t.id + ORDER BY a.expected_epoch::NUMERIC DESC, r.revision_order DESC LIMIT 1 + ) latest ON TRUE + WHERE t.tenant_id = p_legacy_tenant AND t.default_version_id = p_private_version + AND (q.template_id IS NULL OR (latest.operation_kind IS DISTINCT FROM 'DELETE' + AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(snapshot->'entries') e WHERE e->>'templateId' = t.id::TEXT))) + ); +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_template_config_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_template_config_source_genesis%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_template_config_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_template_config_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + template game_templates%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'template config source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'template config genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_template_config_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_template_config_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'template config head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_template_config_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'template config source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_head' 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.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'template config head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'template config staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'template config staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_template_config_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 s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'template config visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected 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 s FROM game_design_template_config_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-template-config-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR NOT template_config_selected_inputs(s.snapshot_json::JSONB, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, s.snapshot_json::JSONB) + OR EXISTS (SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'entries') e + LEFT JOIN game_templates t ON t.id = (e->>'templateId')::BIGINT AND t.tenant_id = v.tenant_id + WHERE t.id IS NULL OR t.config IS DISTINCT FROM (e->>'configJson')::JSONB + OR t.default_version_id IS DISTINCT FROM v.id OR t.default_script_patch_version IS NOT NULL + OR t.default_runtime_flags_json::JSONB IS DISTINCT FROM '{}'::JSONB) + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'template config capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c 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 TG_TABLE_NAME IN ('game_design_template_config_source_qualification', 'game_design_template_config_source_revision', 'game_design_template_config_source_application') THEN + IF NOT 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 AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template config source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME IN ('game_design_template_config_source_qualification', 'game_design_template_config_source_revision') THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id AND tenant_id = v.tenant_id FOR UPDATE; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' THEN + RAISE EXCEPTION 'template revision requires closed exact owner payload' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_qualification' THEN + IF payload->>'operation' IS DISTINCT FROM 'CREATE' OR template.name IS DISTINCT FROM payload->>'templateName' + OR template.config IS DISTINCT FROM (payload->>'configJson')::JSONB OR template.default_version_id IS DISTINCT FROM v.id + OR template.template_reference_phase IS DISTINCT FROM 'LEGACY' + OR template.default_script_patch_version IS NOT NULL OR template.default_runtime_flags_json::JSONB IS DISTINCT FROM '{}'::JSONB + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_row_insert w + WHERE w.template_id = NEW.template_id AND w.creation_transaction_id = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'template qualification requires actual new authorized row' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + IF NEW.payload_json::JSONB IS DISTINCT FROM payload OR NOT template_config_unique_json(NEW.payload_json::JSON) + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q WHERE q.template_id = NEW.template_id + AND q.canonical_tenant_id = NEW.canonical_tenant_id AND q.canonical_version_id = NEW.canonical_version_id) + OR (NEW.operation_kind = 'CREATE' AND NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q + WHERE q.template_id = NEW.template_id AND q.revision_id = NEW.revision_id AND q.request_id = NEW.request_id + AND q.commit_id = NEW.commit_id AND q.revision_order = NEW.revision_order)) + OR (NEW.operation_kind <> 'CREATE' AND payload->>'templateId' IS DISTINCT FROM NEW.template_id::TEXT) THEN + RAISE EXCEPTION 'template revision or canonical association differs' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'DELETE' THEN + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 4 THEN + RAISE EXCEPTION 'template DELETE fields invalid' USING ERRCODE = '23514'; END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_template_config_source_snapshot s0, + LATERAL jsonb_array_elements(s0.snapshot_json::JSONB->'entries') e + WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id + AND s0.commit_id = h.visible_commit_id AND e->>'templateId' = NEW.template_id::TEXT) + AND NOT EXISTS (SELECT 1 FROM game_design_template_config_source_revision r0 + WHERE r0.canonical_tenant_id = NEW.canonical_tenant_id AND r0.canonical_version_id = NEW.canonical_version_id + AND r0.commit_id = NEW.commit_id AND r0.template_id = NEW.template_id + AND r0.revision_order < NEW.revision_order AND r0.operation_kind IN ('CREATE', 'UPSERT')) THEN + RAISE EXCEPTION 'template DELETE requires actual existing authored entry' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR jsonb_typeof(payload->'configJson') IS DISTINCT FROM 'string' + OR NOT template_config_supported(payload->>'configJson', NEW.canonical_version_id) + OR template.config IS DISTINCT FROM (payload->>'configJson')::JSONB THEN + RAISE EXCEPTION 'template config owner inputs unavailable or closed config invalid' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 7 THEN RAISE EXCEPTION 'template config snapshot binding invalid' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'entries' INTO prior FROM game_design_template_config_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'TEMPLATE_CONFIG_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'TEMPLATE_CONFIG_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'template config application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT (item->>'templateId')::BIGINT AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.template_id, r.revision_order, r.operation_kind = 'DELETE', template_config_revision_item(r) + FROM game_design_template_config_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY key) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'entries' THEN + RAISE EXCEPTION 'template config application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'entries' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT template_config_selected_inputs(snapshot, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, snapshot) + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility 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 AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'template config snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION template_config_row_insert_witness() RETURNS TRIGGER AS $$ +BEGIN + INSERT INTO game_design_template_config_source_row_insert VALUES (NEW.id, pg_current_xact_id()::TEXT); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_row_insert_witness AFTER INSERT ON game_templates + FOR EACH ROW EXECUTE FUNCTION template_config_row_insert_witness(); + +CREATE FUNCTION guard_template_config_insert_witness() RETURNS TRIGGER AS $$ +BEGIN + IF pg_trigger_depth() <> 2 OR NEW.creation_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_templates t WHERE t.id = NEW.template_id + AND t.xmin::TEXT = (pg_current_xact_id()::TEXT::XID)::TEXT) THEN + RAISE EXCEPTION 'template insert witness requires actual row insert trigger' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_insert_witness_guard BEFORE INSERT ON game_design_template_config_source_row_insert + FOR EACH ROW EXECUTE FUNCTION guard_template_config_insert_witness(); + +CREATE FUNCTION verify_template_config_explicit_target_row() RETURNS TRIGGER AS $$ +DECLARE template game_templates%ROWTYPE; target version%ROWTYPE; +BEGIN + SELECT * INTO template FROM game_templates WHERE id = NEW.id; + IF NOT FOUND OR template.default_version_id IS NULL THEN RETURN NULL; END IF; + SELECT v.* INTO target FROM version v JOIN game_design_template_config_source_genesis g + ON g.version_id = v.id AND g.canonical_tenant_id = v.canonical_tenant_id AND g.canonical_version_id = v.canonical_version_id + WHERE v.id = template.default_version_id AND v.tenant_id = template.tenant_id FOR UPDATE OF v; + IF NOT FOUND THEN RETURN NULL; END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q + JOIN game_design_template_config_source_revision r ON r.canonical_tenant_id = q.canonical_tenant_id + AND r.canonical_version_id = q.canonical_version_id AND r.revision_id = q.revision_id + AND r.template_id = q.template_id AND r.request_id = q.request_id AND r.commit_id = q.commit_id + AND r.revision_order = q.revision_order AND r.operation_kind = 'CREATE' + WHERE q.template_id = template.id AND q.canonical_tenant_id = target.canonical_tenant_id + AND q.canonical_version_id = target.canonical_version_id) THEN + RAISE EXCEPTION 'explicit template target requires actual authorized CREATE qualification' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER template_config_explicit_target_row_guard AFTER INSERT OR UPDATE ON game_templates + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_explicit_target_row(); + +CREATE FUNCTION guard_template_config_live_row() RETURNS TRIGGER AS $$ +DECLARE q game_design_template_config_source_qualification%ROWTYPE; c game_design_draft_commit%ROWTYPE; + target version%ROWTYPE; payload JSONB; +BEGIN + SELECT * INTO q FROM game_design_template_config_source_qualification WHERE template_id = OLD.id; + IF q.template_id IS NULL THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + IF (NEW.tenant_id, NEW.default_version_id) IS DISTINCT FROM (OLD.tenant_id, OLD.default_version_id) THEN + SELECT v.* INTO target FROM version v JOIN game_design_template_config_source_genesis g + ON g.version_id = v.id AND g.canonical_tenant_id = v.canonical_tenant_id AND g.canonical_version_id = v.canonical_version_id + WHERE v.id = NEW.default_version_id AND v.tenant_id = NEW.tenant_id FOR UPDATE OF v; + IF FOUND THEN RAISE EXCEPTION 'unqualified template cannot be reassigned into managed source target' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + PERFORM 1 FROM version WHERE canonical_tenant_id = q.canonical_tenant_id AND canonical_version_id = q.canonical_version_id FOR UPDATE; + IF TG_OP = 'DELETE' OR NEW.id IS DISTINCT FROM OLD.id OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.name IS DISTINCT FROM OLD.name OR NEW.default_version_id IS DISTINCT FROM OLD.default_version_id + OR NEW.default_script_patch_version IS DISTINCT FROM OLD.default_script_patch_version + OR NEW.default_runtime_flags_json IS DISTINCT FROM OLD.default_runtime_flags_json + OR NEW.template_reference_phase IS DISTINCT FROM OLD.template_reference_phase THEN + RAISE EXCEPTION 'qualified template identity and launch fields immutable' USING ERRCODE = '23514'; END IF; + IF NEW.config IS NOT DISTINCT FROM OLD.config THEN RETURN NEW; END IF; + SELECT owner.* INTO STRICT c FROM game_design_draft_commit owner JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = owner.canonical_tenant_id AND slot.canonical_version_id = owner.canonical_version_id + AND slot.request_id = owner.request_id AND slot.commit_id = owner.commit_id + WHERE owner.canonical_tenant_id = q.canonical_tenant_id AND owner.canonical_version_id = q.canonical_version_id; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection p WHERE p.canonical_tenant_id = q.canonical_tenant_id + AND p.canonical_version_id = q.canonical_version_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r WHERE r.canonical_tenant_id = q.canonical_tenant_id + AND r.canonical_version_id = q.canonical_version_id AND r.request_id = c.request_id + AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'qualified template update requires unfrozen active coordinator' USING ERRCODE = '23514'; END IF; + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (r->>'payload')::JSONB->>'operation' = 'UPSERT' + AND (r->>'payload')::JSONB->>'templateId' = OLD.id::TEXT + AND ((r->>'payload')::JSONB->>'configJson')::JSONB = NEW.config) THEN + RAISE EXCEPTION 'qualified template update differs from bound revision' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_live_row_guard BEFORE UPDATE OR DELETE ON game_templates + FOR EACH ROW EXECUTE FUNCTION guard_template_config_live_row(); + +CREATE FUNCTION verify_template_config_references() RETURNS TRIGGER AS $$ +DECLARE r game_design_template_config_source_revision%ROWTYPE; cfg JSONB; expected JSONB; actual JSONB; + rules JSONB; input JSONB; visible UUID; +BEGIN + SELECT * INTO STRICT r FROM game_design_template_config_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND revision_id = NEW.revision_id; + IF r.operation_kind = 'DELETE' THEN + IF EXISTS (SELECT 1 FROM game_design_template_config_source_ref x WHERE x.canonical_tenant_id = r.canonical_tenant_id + AND x.canonical_version_id = r.canonical_version_id AND x.revision_id = r.revision_id) THEN + RAISE EXCEPTION 'deleted template has no references' USING ERRCODE = '23514'; END IF; + RETURN NULL; + END IF; + cfg := (r.payload_json::JSONB->>'configJson')::JSONB; + SELECT jsonb_agg(value ORDER BY value->>'refKind', value->>'refKey') INTO expected FROM ( + SELECT jsonb_build_object('refKind', 'BASE_VERSION', 'refKey', r.canonical_version_id::TEXT, 'revisionId', NULL) AS value + UNION ALL SELECT jsonb_build_object('refKind', x->>'family', 'refKey', x->>'key', 'revisionId', x->>'revisionId') + FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') x + ) ref_values; + SELECT jsonb_agg(jsonb_build_object('refKind', x.ref_kind, 'refKey', x.ref_key, 'revisionId', x.referenced_revision_id::TEXT) + ORDER BY x.ref_kind, x.ref_key) INTO actual FROM game_design_template_config_source_ref x + WHERE x.canonical_tenant_id = r.canonical_tenant_id AND x.canonical_version_id = r.canonical_version_id AND x.revision_id = r.revision_id; + IF expected IS DISTINCT FROM actual THEN RAISE EXCEPTION 'template normalized references differ from original config' USING ERRCODE = '23514'; END IF; + SELECT snapshot_json::JSONB->'entries' INTO rules FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id AND commit_id = r.commit_id; + IF rules IS NULL THEN + SELECT visible_commit_id INTO visible FROM game_design_gameplay_rule_head + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id; + SELECT snapshot_json::JSONB->'entries' INTO rules FROM game_design_gameplay_rule_snapshot + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id AND commit_id = visible; + END IF; + FOR input IN SELECT * FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') LOOP + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(rules) e WHERE e->>'family' = input->>'family' + AND e->>'revisionId' = input->>'revisionId' + AND gameplay_rule_definition_key(e->>'family', (e->>'definitionJson')::JSONB) = input->>'key') THEN + RAISE EXCEPTION 'template gameplay input not in actual effective source' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER template_config_refs_revision_guard AFTER INSERT ON game_design_template_config_source_revision + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_references(); +CREATE CONSTRAINT TRIGGER template_config_refs_projection_guard AFTER INSERT ON game_design_template_config_source_ref + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_references(); + +CREATE FUNCTION deny_template_config_history_change() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'template source history immutable' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_ref_immutable BEFORE UPDATE OR DELETE ON game_design_template_config_source_ref + FOR EACH ROW EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_insert_witness_immutable BEFORE UPDATE OR DELETE ON game_design_template_config_source_row_insert + FOR EACH ROW EXECUTE FUNCTION deny_template_config_history_change(); +CREATE FUNCTION verify_template_config_application_commit() RETURNS TRIGGER AS $$ +DECLARE branding_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_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 c 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 r 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 h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT count(*) INTO retained FROM game_design_template_config_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-template-config-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'TEMPLATE_CONFIG_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_branding_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_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 c 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 r 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 h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_branding_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'TEMPLATE_CONFIG' AND config_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + branding_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_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 c 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 r 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 h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'TEMPLATE_CONFIG' AND config_bytes IS NULL) OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; branding_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_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 c 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 r 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 h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + SELECT result_bytes INTO policy_bytes 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; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE', 'BRANDING_ASSET_REFERENCE', 'TEMPLATE_CONFIG')) + OR (branding_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE') + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN branding_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN config_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER template_config_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_genesis + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_head + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_revision + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_qualification_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_qualification + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE CONSTRAINT TRIGGER template_config_application_commit_guard AFTER INSERT ON game_design_template_config_source_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_application_commit(); +CREATE TRIGGER template_config_genesis_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_genesis + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_head_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_head + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_revision_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_revision + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_application_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_application + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_snapshot_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_snapshot + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_capture_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_capture + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_qualification_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_qualification + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_ref_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_ref + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_row_insert_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_row_insert + EXECUTE FUNCTION deny_template_config_history_change(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1009__selected_publication_game_logic_receipt.sql b/services/game-design-service/src/main/resources/db/migration/V1009__selected_publication_game_logic_receipt.sql new file mode 100644 index 0000000000..183cd94398 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1009__selected_publication_game_logic_receipt.sql @@ -0,0 +1,52 @@ +-- Derived receipt storage only. Historical selections and publication operations are untouched. +CREATE TABLE game_design_selected_game_logic_receipt ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_request_id VARCHAR(1024) NOT NULL, + selection_digest VARCHAR(71) NOT NULL, + workflow_identity TEXT NOT NULL, + selection_bytes BYTEA NOT NULL, + authorization_bytes BYTEA NOT NULL, + authorization_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, publish_request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, publish_request_id) + REFERENCES game_design_authored_draft_publish_selection + (canonical_tenant_id, canonical_version_id, publish_request_id) ON DELETE RESTRICT, + CHECK (selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (workflow_identity = 'publish:' || canonical_tenant_id::text || ':publish-request:' || publish_request_id), + CHECK (octet_length(selection_bytes) BETWEEN 1 AND 8388608), + CHECK (octet_length(authorization_bytes) BETWEEN 1 AND 4194304), + CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 16778240) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_selected_game_logic_receipt() RETURNS trigger AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Selected Game Logic receipts are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT 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 + AND s.publish_request_id = NEW.publish_request_id + AND s.selection_digest = NEW.selection_digest + AND convert_to(s.selection_json, 'UTF8') = NEW.selection_bytes + ) THEN + RAISE EXCEPTION 'Receipt requires exact existing immutable selection' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_selected_game_logic_receipt + BEFORE INSERT OR UPDATE OR DELETE ON game_design_selected_game_logic_receipt + FOR EACH ROW EXECUTE FUNCTION enforce_gd_selected_game_logic_receipt(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1010__selected_template_world_source_association.sql b/services/game-design-service/src/main/resources/db/migration/V1010__selected_template_world_source_association.sql new file mode 100644 index 0000000000..fb9b54f847 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1010__selected_template_world_source_association.sql @@ -0,0 +1,105 @@ +-- One immutable World-source relation for every template actually present in the selected capture. +CREATE TABLE game_design_selected_template_world_source_association ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + template_id BIGINT NOT NULL REFERENCES game_templates (id) ON DELETE RESTRICT, + publish_workflow_id VARCHAR(1024) NOT NULL + REFERENCES game_design_publication_operation (publish_workflow_id) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + world_operation_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + operation_bytes BYTEA NOT NULL, + capture_bytes BYTEA NOT NULL, + template_snapshot_bytes BYTEA NOT NULL, + template_entry_bytes BYTEA NOT NULL, + world_read_request_bytes BYTEA NOT NULL, + world_read_response_bytes BYTEA NOT NULL, + association_bytes BYTEA NOT NULL, + association_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id, template_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_template_config_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_capture + (canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND template_id > 0 + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (octet_length(operation_bytes) > 0 + AND octet_length(capture_bytes) > 0 + AND octet_length(template_snapshot_bytes) > 0 + AND octet_length(template_entry_bytes) > 0 + AND octet_length(world_read_request_bytes) > 0 + AND octet_length(world_read_response_bytes) > 0 + AND octet_length(association_bytes) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_selected_template_world_source_association() RETURNS trigger AS $$ +DECLARE + op RECORD; + capture RECORD; + snapshot RECORD; + matching_entry BOOLEAN; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Selected template/world source associations are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT op + FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id + FOR UPDATE; + SELECT * INTO STRICT capture + FROM game_design_template_config_source_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot + FROM game_design_template_config_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 EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot.snapshot_json::JSONB -> 'entries') entry + WHERE entry ->> 'templateId' = NEW.template_id::TEXT + AND entry = convert_from(NEW.template_entry_bytes, 'UTF8')::JSONB + ) INTO matching_entry; + + IF op.outcome <> 'PENDING' + OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.commit_id IS DISTINCT FROM NEW.commit_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR convert_to(snapshot.snapshot_json, 'UTF8') IS DISTINCT FROM NEW.template_snapshot_bytes + OR NOT matching_entry + OR NEW.association_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.association_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected template/world source association differs from its exact pending capture' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_selected_template_world_source_association + BEFORE INSERT OR UPDATE OR DELETE ON game_design_selected_template_world_source_association + FOR EACH ROW EXECUTE FUNCTION enforce_gd_selected_template_world_source_association(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1011__selected_publication_control_plane_digest_schema.sql b/services/game-design-service/src/main/resources/db/migration/V1011__selected_publication_control_plane_digest_schema.sql new file mode 100644 index 0000000000..34bd2cf9b9 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1011__selected_publication_control_plane_digest_schema.sql @@ -0,0 +1,202 @@ +-- Selected full publications use the immutable six-source control-plane digest schema. +-- Replacing this function keeps the retained V1 policy and all other V2 checks unchanged. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version <> 'v2' THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'release v2 requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'release v2 World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'release v2 requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'release v2 requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'release v2 owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'release v2 selector differs from original selected APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'release v2 requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',3),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'release v2 has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'release v2 participant differs from selected commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1012__normalized_template_references_and_tenant_phase.sql b/services/game-design-service/src/main/resources/db/migration/V1012__normalized_template_references_and_tenant_phase.sql new file mode 100644 index 0000000000..4bc3c533e7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1012__normalized_template_references_and_tenant_phase.sql @@ -0,0 +1,410 @@ +ALTER TABLE game_design_template_config_source_revision + ADD CONSTRAINT uq_template_config_revision_source_binding + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_id, template_id); + +CREATE TABLE game_template_version_ref ( + canonical_tenant_id UUID NOT NULL, + template_id BIGINT NOT NULL, + canonical_version_id UUID NOT NULL, + source_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + PRIMARY KEY (canonical_tenant_id, template_id), + FOREIGN KEY (template_id) + REFERENCES game_design_template_config_source_qualification (template_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id) + ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_template_config_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id, source_revision_id, template_id) + REFERENCES game_design_template_config_source_revision + (canonical_tenant_id, canonical_version_id, commit_id, revision_id, template_id) + ON DELETE RESTRICT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); +CREATE INDEX ix_game_template_version_ref_version + ON game_template_version_ref (canonical_tenant_id, canonical_version_id, template_id); + +CREATE TABLE game_template_reference_phase ( + canonical_tenant_id UUID PRIMARY KEY REFERENCES game (canonical_tenant_id) ON DELETE RESTRICT, + source_game_row_id BIGINT NOT NULL REFERENCES game (id) ON DELETE RESTRICT, + source_game_tenant_key VARCHAR(36) NOT NULL, + creation_operation_id UUID NOT NULL UNIQUE + REFERENCES game_tenant_creation_operations (operation_id) ON DELETE RESTRICT, + creation_request_id UUID NOT NULL, + creation_evidence_digest VARCHAR(71) NOT NULL, + phase VARCHAR(16) NOT NULL, + phase_epoch BIGINT NOT NULL, + inventory_digest VARCHAR(71), + inventory_template_count BIGINT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (source_game_row_id > 0), + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + CHECK (creation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (phase IN ('BACKFILLING', 'VALIDATED', 'ENFORCED')), + CHECK (phase_epoch > 0), + CHECK ( + (phase = 'BACKFILLING' AND inventory_digest IS NULL AND inventory_template_count IS NULL) + OR (phase IN ('VALIDATED', 'ENFORCED') + AND inventory_digest IS NOT NULL + AND inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_template_count IS NOT NULL + AND inventory_template_count > 0) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_template_reference_phase() RETURNS TRIGGER AS $$ +DECLARE creation game_tenant_creation_operations%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'template reference phase authority is retained' USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT creation + FROM game_tenant_creation_operations + WHERE operation_id = NEW.creation_operation_id; + IF NEW.phase <> 'BACKFILLING' OR NEW.phase_epoch <> 1 + OR NEW.inventory_digest IS NOT NULL OR NEW.inventory_template_count IS NOT NULL + OR creation.status <> 'COMPLETED' + OR creation.operation_id <> NEW.creation_operation_id + OR creation.creation_request_id <> NEW.creation_request_id + OR creation.canonical_tenant_id <> NEW.canonical_tenant_id + OR creation.source_game_row_id <> NEW.source_game_row_id + OR creation.source_game_tenant_key <> NEW.source_game_tenant_key + OR creation.provenance_kind <> 'NEW_GAME_ROW' + OR creation.evidence_digest <> NEW.creation_evidence_digest + OR NOT EXISTS ( + SELECT 1 FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = 'NEW_GAME_ROW' + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'template reference phase requires exact fresh Game creation evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + 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.creation_operation_id IS DISTINCT FROM OLD.creation_operation_id + OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.phase_epoch <> OLD.phase_epoch + 1 + OR NOT ( + (OLD.phase = 'BACKFILLING' AND NEW.phase = 'VALIDATED' + AND NEW.inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND NEW.inventory_template_count > 0) + OR (OLD.phase = 'VALIDATED' AND NEW.phase = 'ENFORCED' + AND NEW.inventory_digest = OLD.inventory_digest + AND NEW.inventory_template_count = OLD.inventory_template_count) + ) THEN + RAISE EXCEPTION 'template reference phase requires a monotonic evidence-backed CAS transition' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_reference_phase_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_template_reference_phase + FOR EACH ROW EXECUTE FUNCTION guard_game_template_reference_phase(); + +CREATE FUNCTION reject_game_template_reference_phase_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'template reference phase authority cannot be truncated' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_template_reference_phase_no_truncate + BEFORE TRUNCATE ON game_template_reference_phase + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_template_reference_phase_truncate(); + +CREATE FUNCTION lock_and_guard_game_template_reference_write() RETURNS TRIGGER AS $$ +DECLARE owner game%ROWTYPE; old_phase game_template_reference_phase%ROWTYPE; + new_phase game_template_reference_phase%ROWTYPE; + active_create BOOLEAN; active_upsert BOOLEAN; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + PERFORM id FROM game WHERE tenant_id IN (OLD.tenant_id, NEW.tenant_id) ORDER BY id FOR UPDATE; + SELECT p.* INTO old_phase FROM game_template_reference_phase p + JOIN game g ON g.canonical_tenant_id = p.canonical_tenant_id + WHERE g.tenant_id = OLD.tenant_id; + SELECT p.* INTO new_phase FROM game_template_reference_phase p + JOIN game g ON g.canonical_tenant_id = p.canonical_tenant_id + WHERE g.tenant_id = NEW.tenant_id; + IF old_phase.canonical_tenant_id IS NOT NULL OR new_phase.canonical_tenant_id IS NOT NULL THEN + RAISE EXCEPTION 'template tenant cannot change after reference phase authority exists' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + SELECT * INTO owner FROM game WHERE tenant_id = OLD.tenant_id FOR UPDATE; + ELSE + SELECT * INTO owner FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + END IF; + IF NOT FOUND OR owner.canonical_tenant_id IS NULL THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; + END IF; + + SELECT * INTO new_phase FROM game_template_reference_phase + WHERE canonical_tenant_id = owner.canonical_tenant_id; + IF NOT FOUND OR new_phase.phase = 'BACKFILLING' THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'validated template rows require an owner source tombstone' + USING ERRCODE = '23514'; + END IF; + + active_create := FALSE; + active_upsert := FALSE; + IF TG_OP = 'INSERT' THEN + SELECT EXISTS ( + SELECT 1 + FROM version v + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = v.canonical_tenant_id + AND c.canonical_version_id = v.canonical_version_id + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + CROSS JOIN LATERAL jsonb_array_elements(c.binding_json::JSONB->'revisions') revision + WHERE v.id = NEW.default_version_id AND v.tenant_id = NEW.tenant_id + AND v.canonical_tenant_id = owner.canonical_tenant_id + AND c.canonical_tenant_id = owner.canonical_tenant_id + AND revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (revision->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (revision->>'payload')::JSONB->>'operation' = 'CREATE' + AND (revision->>'payload')::JSONB->>'templateName' = NEW.name + AND ((revision->>'payload')::JSONB->>'configJson')::JSONB = NEW.config + ) INTO active_create; + IF NOT active_create THEN + RAISE EXCEPTION 'validated template create requires exact active owner source binding' + USING ERRCODE = '23514'; + END IF; + ELSE + SELECT EXISTS ( + SELECT 1 + FROM game_design_template_config_source_qualification q + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = q.canonical_tenant_id + AND c.canonical_version_id = q.canonical_version_id + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + CROSS JOIN LATERAL jsonb_array_elements(c.binding_json::JSONB->'revisions') revision + WHERE q.template_id = OLD.id AND q.canonical_tenant_id = owner.canonical_tenant_id + AND c.canonical_tenant_id = owner.canonical_tenant_id + AND revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (revision->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (revision->>'payload')::JSONB->>'operation' = 'UPSERT' + AND (revision->>'payload')::JSONB->>'templateId' = OLD.id::TEXT + AND ((revision->>'payload')::JSONB->>'configJson')::JSONB = NEW.config + ) INTO active_upsert; + IF NEW.id IS DISTINCT FROM OLD.id OR NEW.name IS DISTINCT FROM OLD.name + OR NEW.default_version_id IS DISTINCT FROM OLD.default_version_id + OR NEW.default_script_patch_version IS DISTINCT FROM OLD.default_script_patch_version + OR NEW.default_runtime_flags_json IS DISTINCT FROM OLD.default_runtime_flags_json + OR NEW.template_reference_phase IS DISTINCT FROM OLD.template_reference_phase + OR NOT active_upsert THEN + RAISE EXCEPTION 'validated template update requires exact active owner source binding' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_reference_tenant_mutex_and_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_templates + FOR EACH ROW EXECUTE FUNCTION lock_and_guard_game_template_reference_write(); + +CREATE FUNCTION guard_game_template_version_ref() RETURNS TRIGGER AS $$ +DECLARE owner game%ROWTYPE; template game_templates%ROWTYPE; target version%ROWTYPE; + revision game_design_template_config_source_revision%ROWTYPE; +BEGIN + SELECT * INTO owner FROM game WHERE canonical_tenant_id = + CASE WHEN TG_OP = 'DELETE' THEN OLD.canonical_tenant_id ELSE NEW.canonical_tenant_id END FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'normalized template reference lacks exact Game owner' USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id; + SELECT * INTO STRICT target FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT revision FROM game_design_template_config_source_revision + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.source_commit_id + AND revision_id = NEW.source_revision_id + AND template_id = NEW.template_id; + IF template.tenant_id <> owner.tenant_id + OR template.default_version_id <> target.id + OR target.tenant_id <> owner.tenant_id + OR target.identity_source_game_row_id <> owner.id + OR target.identity_source_game_tenant_key <> owner.tenant_id + OR target.identity_source_provenance_kind <> owner.tenant_identity_provenance_kind + OR revision.operation_kind NOT IN ('CREATE', 'UPSERT') + OR NOT EXISTS ( + SELECT 1 FROM game_design_template_config_source_ref ref + WHERE ref.canonical_tenant_id = NEW.canonical_tenant_id + AND ref.canonical_version_id = NEW.canonical_version_id + AND ref.revision_id = NEW.source_revision_id + AND ref.ref_kind = 'BASE_VERSION' + AND ref.ref_key = NEW.canonical_version_id::TEXT + AND ref.referenced_revision_id IS NULL + ) + OR NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id + AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = revision.request_id + AND c.commit_id = NEW.source_commit_id + ) + OR ((revision.payload_json::JSONB)->>'configJson')::JSONB IS DISTINCT FROM template.config THEN + RAISE EXCEPTION 'normalized template base reference differs from exact authorized source' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.template_id IS DISTINCT FROM NEW.template_id + OR OLD.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id THEN + RAISE EXCEPTION 'normalized template base identity is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id; + SELECT * INTO STRICT target FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT revision FROM game_design_template_config_source_revision + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.source_commit_id + AND revision_id = NEW.source_revision_id + AND template_id = NEW.template_id; + IF template.tenant_id <> owner.tenant_id + OR template.default_version_id <> target.id + OR target.tenant_id <> owner.tenant_id + OR target.identity_source_game_row_id <> owner.id + OR target.identity_source_game_tenant_key <> owner.tenant_id + OR target.identity_source_provenance_kind <> owner.tenant_identity_provenance_kind + OR revision.operation_kind <> 'UPSERT' + OR NOT EXISTS ( + SELECT 1 FROM game_design_template_config_source_ref ref + WHERE ref.canonical_tenant_id = NEW.canonical_tenant_id + AND ref.canonical_version_id = NEW.canonical_version_id + AND ref.revision_id = NEW.source_revision_id + AND ref.ref_kind = 'BASE_VERSION' + AND ref.ref_key = NEW.canonical_version_id::TEXT + AND ref.referenced_revision_id IS NULL + ) + OR NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id + AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = revision.request_id + AND c.commit_id = NEW.source_commit_id + ) + OR ((revision.payload_json::JSONB)->>'configJson')::JSONB IS DISTINCT FROM template.config THEN + RAISE EXCEPTION 'normalized template base update differs from exact owner upsert' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + SELECT r.* INTO STRICT revision + FROM game_design_draft_commit_application_slot slot + JOIN game_design_template_config_source_revision r + ON r.canonical_tenant_id = slot.canonical_tenant_id + AND r.canonical_version_id = slot.canonical_version_id + AND r.request_id = slot.request_id AND r.commit_id = slot.commit_id + WHERE slot.canonical_tenant_id = OLD.canonical_tenant_id + AND slot.canonical_version_id = OLD.canonical_version_id + AND r.template_id = OLD.template_id AND r.operation_kind = 'DELETE'; + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = OLD.canonical_tenant_id + AND c.canonical_version_id = OLD.canonical_version_id + AND c.commit_id = revision.commit_id + AND c.request_id = revision.request_id + ) THEN + RAISE EXCEPTION 'normalized template base removal requires exact active source tombstone' + USING ERRCODE = '23514'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_version_ref_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_template_version_ref + FOR EACH ROW EXECUTE FUNCTION guard_game_template_version_ref(); + +CREATE FUNCTION reject_game_template_version_ref_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'normalized template references cannot be truncated' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_template_version_ref_no_truncate + BEFORE TRUNCATE ON game_template_version_ref + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_template_version_ref_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1013__selected_inventory_asset_export_candidate.sql b/services/game-design-service/src/main/resources/db/migration/V1013__selected_inventory_asset_export_candidate.sql new file mode 100644 index 0000000000..f37fb911a9 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1013__selected_inventory_asset_export_candidate.sql @@ -0,0 +1,122 @@ +CREATE TABLE version_asset_export_candidate ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + expected_version_state_epoch BIGINT NOT NULL, + workflow_id VARCHAR(1024) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + request_preimage BYTEA NOT NULL, + operation_digest VARCHAR(71) NOT NULL, + selected_commit_digest VARCHAR(71) NOT NULL, + inventory_schema VARCHAR(128) NOT NULL, + inventory_digest VARCHAR(71) NOT NULL, + inventory_bytes BYTEA NOT NULL, + manifest_schema_version INTEGER NOT NULL, + manifest_hash VARCHAR(71) NOT NULL, + manifest_bytes BYTEA NOT NULL, + artifact_digests_json TEXT NOT NULL, + required_usage_keys_json TEXT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset_export_candidate PRIMARY KEY (tenant_id, version_id), + CONSTRAINT fk_version_asset_export_candidate_version + FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_export_candidate_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_version_state_epoch > 0 + AND char_length(workflow_id) > 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND operation_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_commit_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_schema = 'game-design-selected-draft-asset-inventory/v1' + AND inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(request_preimage) > 0 + AND octet_length(inventory_bytes) > 0 + AND manifest_schema_version = 1 + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(manifest_bytes) > 0 + AND artifact_digests_json::JSONB IS NOT NULL + AND required_usage_keys_json::JSONB IS NOT NULL + ) +); + +CREATE INDEX idx_version_asset_export_candidate_request + ON version_asset_export_candidate (canonical_tenant_id, version_id, request_digest); + +-- Candidate rows are the additive selected-inventory shape. V37 snapshot candidates remain +-- untouched and no retained V37 data is synthesized into this new evidence table. +-- [jooq ignore start] +CREATE FUNCTION guard_version_asset_export_candidate() RETURNS TRIGGER AS $$ +DECLARE + version_state_value VARCHAR(32); + version_epoch_value BIGINT; + version_canonical_tenant UUID; + version_canonical_version UUID; + source_game_id BIGINT; + source_game_tenant VARCHAR(36); + source_provenance VARCHAR(64); + game_canonical_tenant UUID; + game_provenance VARCHAR(64); + game_source_id BIGINT; + game_source_tenant VARCHAR(36); +BEGIN + IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + + SELECT v.version_state, v.version_state_epoch, 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, + g.canonical_tenant_id, g.tenant_identity_provenance_kind, + g.tenant_identity_source_game_id, g.tenant_identity_source_legacy_tenant_id + INTO version_state_value, version_epoch_value, version_canonical_tenant, + version_canonical_version, source_game_id, source_game_tenant, + source_provenance, game_canonical_tenant, game_provenance, + game_source_id, game_source_tenant + 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.tenant_id = v.tenant_id + 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.tenant_id = NEW.tenant_id AND v.id = NEW.version_id + FOR UPDATE OF v, g; + + IF NOT FOUND OR version_state_value <> 'DRAFT' + OR version_epoch_value IS DISTINCT FROM NEW.expected_version_state_epoch + OR version_canonical_tenant IS DISTINCT FROM NEW.canonical_tenant_id + OR version_canonical_version IS DISTINCT FROM NEW.canonical_version_id + OR source_game_id IS NULL OR source_game_tenant IS DISTINCT FROM NEW.tenant_id + OR source_provenance IS NULL + OR game_canonical_tenant IS DISTINCT FROM NEW.canonical_tenant_id + OR game_provenance IS DISTINCT FROM source_provenance + OR game_source_id IS DISTINCT FROM source_game_id + OR game_source_tenant IS DISTINCT FROM source_game_tenant THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_SCOPE_CONFLICT'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_candidate_immutable + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_candidate + FOR EACH ROW EXECUTE FUNCTION guard_version_asset_export_candidate(); + +CREATE FUNCTION guard_version_asset_export_candidate_truncate() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version_asset_export_candidate) THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_candidate_no_truncate + BEFORE TRUNCATE ON version_asset_export_candidate + FOR EACH STATEMENT EXECUTE FUNCTION guard_version_asset_export_candidate_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1014__start_session_launch_descriptor_association_binding.sql b/services/game-design-service/src/main/resources/db/migration/V1014__start_session_launch_descriptor_association_binding.sql new file mode 100644 index 0000000000..52af26bd9b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1014__start_session_launch_descriptor_association_binding.sql @@ -0,0 +1,219 @@ +-- A new exact StartSession descriptor is inseparable from the original Account/GS execution and +-- the immutable selected template/source association that authorized its launch target. +CREATE TABLE game_design_start_session_launch_descriptor_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(255) NOT NULL, + launch_descriptor_row_id BIGINT NOT NULL UNIQUE + REFERENCES launch_descriptor (id) ON DELETE RESTRICT, + release_bundle_id BIGINT NOT NULL + REFERENCES published_release_bundle (id) ON DELETE RESTRICT, + version_state_epoch BIGINT NOT NULL, + canonical_post_authorization_tuple BYTEA NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL, + publication_selection_digest VARCHAR(71) NOT NULL, + association_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL + REFERENCES game_design_authored_world_source_operations (operation_id) ON DELETE RESTRICT, + source_evidence_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + reference_phase_epoch BIGINT NOT NULL, + runtime_surface VARCHAR(32) NOT NULL, + game_logic_publish_request_id VARCHAR(1024) NOT NULL, + game_logic_selection_digest VARCHAR(71) NOT NULL, + game_logic_authorization_digest VARCHAR(71) NOT NULL, + game_logic_receipt_digest VARCHAR(71) NOT NULL, + association_read_response_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_start_session_launch_descriptor_binding PRIMARY KEY ( + target_namespace, + canonical_tenant_id, + control_plane_request_id + ), + CONSTRAINT fk_gd_start_session_launch_association FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_id, + game_template_id + ) REFERENCES game_design_selected_template_world_source_association ( + canonical_tenant_id, + canonical_version_id, + commit_id, + template_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_gd_start_session_launch_game_logic_receipt FOREIGN KEY ( + canonical_tenant_id, + game_logic_publish_request_id + ) REFERENCES game_design_selected_game_logic_receipt ( + canonical_tenant_id, + publish_request_id + ) ON DELETE RESTRICT, + CONSTRAINT ck_gd_start_session_launch_binding_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND control_plane_request_id !~ '^[[:space:]]*$' + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND octet_length(canonical_post_authorization_tuple) BETWEEN 1 AND 262144 + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND game_template_id > 0 + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND char_length(publish_workflow_id) BETWEEN 1 AND 1024 + AND publication_selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND reference_phase_epoch > 0 + AND runtime_surface IN ('EMPTY_V1', 'UNSUPPORTED_CAPTURE_V1') + AND char_length(game_logic_publish_request_id) BETWEEN 1 AND 1024 + AND game_logic_selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_logic_authorization_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_logic_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(association_read_response_bytes) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_gd_start_session_launch_descriptor_binding() RETURNS trigger AS $$ +DECLARE descriptor launch_descriptor%ROWTYPE; + association game_design_selected_template_world_source_association%ROWTYPE; + current_version version%ROWTYPE; + current_phase game_template_reference_phase%ROWTYPE; + publication game_design_publication_operation%ROWTYPE; + owner_source game_design_authored_world_source_operations%ROWTYPE; + release published_release_bundle%ROWTYPE; + game_logic_receipt game_design_selected_game_logic_receipt%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession launch descriptor bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT descriptor + FROM launch_descriptor + WHERE id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT association + FROM game_design_selected_template_world_source_association + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.selected_commit_id + AND template_id = NEW.game_template_id; + SELECT * INTO STRICT current_version + FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT current_phase + FROM game_template_reference_phase + WHERE canonical_tenant_id = NEW.canonical_tenant_id; + SELECT * INTO STRICT publication + FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + SELECT * INTO STRICT owner_source + FROM game_design_authored_world_source_operations + WHERE operation_id = NEW.source_operation_id; + SELECT * INTO STRICT release + FROM published_release_bundle + WHERE id = NEW.release_bundle_id; + SELECT * INTO STRICT game_logic_receipt + FROM game_design_selected_game_logic_receipt + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND publish_request_id = NEW.game_logic_publish_request_id; + + IF descriptor.outcome_status NOT IN ('SUCCESS', 'FAILED') + OR descriptor.descriptor_schema_version <> 1 + OR descriptor.target_namespace IS DISTINCT FROM NEW.target_namespace + OR descriptor.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR descriptor.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor.tenant_id IS DISTINCT FROM owner_source.source_game_tenant_key + OR current_version.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR current_version.version_state NOT IN ('PUBLISHED', 'ACTIVE') + OR current_version.is_script_only IS DISTINCT FROM FALSE + OR current_version.script_patch_version IS NOT NULL + OR current_phase.phase IS DISTINCT FROM 'ENFORCED' + OR current_phase.phase_epoch IS DISTINCT FROM NEW.reference_phase_epoch + OR publication.outcome IS DISTINCT FROM 'PUBLISHED' + OR publication.selection_digest IS DISTINCT FROM NEW.publication_selection_digest + OR owner_source.target_namespace IS DISTINCT FROM NEW.target_namespace + OR owner_source.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR owner_source.world_slug IS DISTINCT FROM NEW.world_slug + OR owner_source.evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR owner_source.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR owner_source.source_game_row_id IS DISTINCT FROM current_phase.source_game_row_id + OR owner_source.source_game_tenant_key IS DISTINCT FROM current_phase.source_game_tenant_key + OR release.tenant_id IS DISTINCT FROM current_version.tenant_id + OR release.version_id IS DISTINCT FROM current_version.id + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR game_logic_receipt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR game_logic_receipt.selection_digest IS DISTINCT FROM NEW.game_logic_selection_digest + OR game_logic_receipt.selection_digest IS DISTINCT FROM NEW.publication_selection_digest + OR game_logic_receipt.authorization_digest IS DISTINCT FROM NEW.game_logic_authorization_digest + OR game_logic_receipt.receipt_digest IS DISTINCT FROM NEW.game_logic_receipt_digest + OR game_logic_receipt.workflow_identity IS DISTINCT FROM NEW.publish_workflow_id + OR descriptor.authored_world_source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR descriptor.authored_world_source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR descriptor.world_slug IS DISTINCT FROM NEW.world_slug + OR association.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR association.target_namespace IS DISTINCT FROM NEW.target_namespace + OR association.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR association.commit_id IS DISTINCT FROM NEW.selected_commit_id + OR association.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR association.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR association.world_slug IS DISTINCT FROM NEW.world_slug + OR association.association_digest IS DISTINCT FROM NEW.association_digest + OR (descriptor.outcome_status = 'SUCCESS' AND ( + NEW.runtime_surface IS DISTINCT FROM 'EMPTY_V1' + OR descriptor.game_template_id IS DISTINCT FROM NEW.game_template_id + OR descriptor.version_id IS DISTINCT FROM current_version.id + OR descriptor.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR descriptor.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR descriptor.published_release_bundle_ref IS DISTINCT FROM release.published_release_bundle_ref + OR descriptor.generation_config_revision IS DISTINCT FROM release.generation_config_revision + OR descriptor.failure_code IS NOT NULL + OR descriptor.failure_message IS NOT NULL + OR descriptor.result_digest IS NULL + )) + OR (descriptor.outcome_status = 'FAILED' AND ( + NEW.runtime_surface IS DISTINCT FROM 'UNSUPPORTED_CAPTURE_V1' + OR descriptor.failure_code IS DISTINCT FROM 'INVALID_TEMPLATE_CONFIGURATION' + OR descriptor.failure_message IS DISTINCT FROM + 'INVALID_TEMPLATE_CONFIGURATION: captured template has unsupported World, Entity, or Automation references' + OR descriptor.game_template_id IS NOT NULL + OR descriptor.version_id IS NOT NULL + OR descriptor.script_patch_version IS NOT NULL + OR descriptor.runtime_flags_json IS NOT NULL + OR descriptor.generation_config_revision IS NOT NULL + OR descriptor.version_state_epoch IS NOT NULL + OR descriptor.release_bundle_id IS NOT NULL + OR descriptor.published_release_bundle_ref IS NOT NULL + OR descriptor.remap_set_id IS NOT NULL + OR descriptor.result_digest IS NOT NULL + )) THEN + RAISE EXCEPTION 'StartSession launch descriptor binding differs from exact immutable owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_launch_descriptor_binding + BEFORE INSERT OR UPDATE OR DELETE ON game_design_start_session_launch_descriptor_binding + FOR EACH ROW EXECUTE FUNCTION guard_gd_start_session_launch_descriptor_binding(); + +CREATE FUNCTION reject_gd_start_session_launch_descriptor_binding_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession launch descriptor bindings are retained' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_launch_descriptor_binding_no_truncate + BEFORE TRUNCATE ON game_design_start_session_launch_descriptor_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_start_session_launch_descriptor_binding_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1015__template_config_owner_source_inventory.sql b/services/game-design-service/src/main/resources/db/migration/V1015__template_config_owner_source_inventory.sql new file mode 100644 index 0000000000..1dd3eb066d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1015__template_config_owner_source_inventory.sql @@ -0,0 +1,365 @@ +CREATE TABLE game_design_template_config_owner_source_inventory_declaration ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), + owner VARCHAR(32) NOT NULL CHECK (owner = 'AUTOMATION_SCRIPTING'), + inventory_json TEXT NOT NULL, + payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, owner), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id, owner), + 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, commit_id) + REFERENCES game_design_template_config_source_application + (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (commit_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (revision_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (octet_length(inventory_json) BETWEEN 1 AND 4096), + CHECK (octet_length(payload_json) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION automation_authored_source_inventory_supported(value JSONB) RETURNS BOOLEAN AS $$ +BEGIN + IF jsonb_typeof(value) IS DISTINCT FROM 'object' THEN RETURN FALSE; END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value)) <> 2 + OR value->>'schema' IS DISTINCT FROM 'automation-authored-source-inventory/v1' + OR jsonb_typeof(value->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(value->'families') IS DISTINCT FROM 'object' THEN RETURN FALSE; END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value->'families')) <> 3 + OR jsonb_typeof(value->'families'->'SCRIPT_DEFINITIONS') IS DISTINCT FROM 'array' + OR jsonb_typeof(value->'families'->'EVENT_BINDINGS') IS DISTINCT FROM 'array' + OR jsonb_typeof(value->'families'->'SCRIPT_PATCH_SOURCES') IS DISTINCT FROM 'array' THEN RETURN FALSE; END IF; + IF jsonb_array_length(value->'families'->'SCRIPT_DEFINITIONS') <> 0 + OR jsonb_array_length(value->'families'->'EVENT_BINDINGS') <> 0 + OR jsonb_array_length(value->'families'->'SCRIPT_PATCH_SOURCES') <> 0 THEN RETURN FALSE; END IF; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION guard_template_config_owner_source_inventory_declaration() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; c game_design_draft_commit%ROWTYPE; revision JSONB; payload JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_genesis g + WHERE g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.canonical_version_id = NEW.canonical_version_id AND g.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c 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 NOT 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 + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template owner inventory requires active coordinator application' USING ERRCODE = '23514'; + END IF; + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF jsonb_typeof(payload) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template owner inventory requires exact supported Automation declaration' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR payload->'schemaVersion' IS DISTINCT FROM '2'::JSONB + OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' + OR payload->>'operation' IS DISTINCT FROM 'DECLARE_OWNER_SOURCE_INVENTORY' + OR payload->>'owner' IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR jsonb_typeof(payload->'inventory') IS DISTINCT FROM 'object' + OR NEW.owner IS DISTINCT FROM payload->>'owner' + OR NEW.inventory_json::JSONB IS DISTINCT FROM payload->'inventory' + OR NOT template_config_unique_json(NEW.inventory_json::JSON) + OR NOT automation_authored_source_inventory_supported(NEW.inventory_json::JSONB) + OR NEW.payload_json IS DISTINCT FROM revision->>'payload' + OR NEW.payload_json::JSONB IS DISTINCT FROM payload THEN + RAISE EXCEPTION 'template owner inventory requires exact supported Automation declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_template_config_v1_snapshot_declaration_presence() RETURNS TRIGGER AS $$ +DECLARE source_epoch TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + IF NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v1' THEN + RETURN NEW; + END IF; + source_epoch := NEW.snapshot_json::JSONB->>'sourceEpoch'; + IF EXISTS (SELECT 1 FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = d.canonical_tenant_id + AND a.canonical_version_id = d.canonical_version_id AND a.request_id = d.request_id AND a.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND a.expected_epoch::NUMERIC < source_epoch::NUMERIC) THEN + RAISE EXCEPTION 'template config v1 snapshot cannot omit retained owner declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_template_config_source_v2() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_template_config_source_genesis%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_template_config_source_application%ROWTYPE; snapshot JSONB; prior JSONB; + expected_items JSONB; expected_declarations JSONB; declared BIGINT; predecessor_commit_id UUID; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'template config source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT g FROM game_design_template_config_source_genesis + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT h FROM game_design_template_config_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template config source is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c 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; + snapshot := NEW.snapshot_json::JSONB; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template config v2 snapshot binding invalid' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json(NEW.snapshot_json::JSON) + OR snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json + OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN + RAISE EXCEPTION 'template config v2 snapshot binding invalid' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR jsonb_typeof(snapshot->'ownerSourceInventoryDeclarations') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot->'ownerSourceInventoryDeclarations') = 0 THEN + RAISE EXCEPTION 'template config v2 snapshot declarations are required' USING ERRCODE = '23514'; + END IF; + + -- The application is checked against the pre-application head; its later synchronized + -- snapshot inherits from that immutable application, not a head pointer that may advance. + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + predecessor_commit_id := h.visible_commit_id; + ELSE + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT * INTO a FROM game_design_template_config_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF (declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) THEN + RAISE EXCEPTION 'template config v2 snapshot differs from its validated application' USING ERRCODE = '23514'; + END IF; + IF a.commit_id IS NOT NULL THEN + predecessor_commit_id := NULLIF(a.snapshot_json::JSONB->>'inheritedCommitId', '')::UUID; + ELSE + predecessor_commit_id := h.visible_commit_id; + END IF; + END IF; + IF snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(predecessor_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'template config v2 predecessor binding invalid' USING ERRCODE = '23514'; + END IF; + SELECT s0.snapshot_json::JSONB INTO prior + FROM (SELECT 1) seed + LEFT JOIN game_design_template_config_source_snapshot s0 ON s0.canonical_tenant_id = NEW.canonical_tenant_id + AND s0.canonical_version_id = NEW.canonical_version_id + AND s0.commit_id = predecessor_commit_id; + IF predecessor_commit_id IS NOT NULL AND prior IS NULL THEN + RAISE EXCEPTION 'template config v2 predecessor snapshot is unavailable' USING ERRCODE = '23514'; + END IF; + IF prior IS NULL THEN + prior := jsonb_build_object( + 'entries', '[]'::JSONB, + 'ownerSourceInventoryDeclarations', '[]'::JSONB); + END IF; + + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + IF NOT 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 + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) + OR NEW.expected_epoch IS DISTINCT FROM h.source_epoch + OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'TEMPLATE_CONFIG_SET' + AND unit->>'aggregateId' = NEW.canonical_version_id::TEXT + AND unit->>'scopeType' = 'TEMPLATE_CONFIG_SET' + AND unit->>'scopeId' = 'effective' + AND unit->>'expectedEpoch' = NEW.expected_epoch) <> 1 THEN + RAISE EXCEPTION 'template config v2 application lacks coordinator scope epoch' USING ERRCODE = '23514'; + END IF; + WITH choices AS ( + SELECT (item->>'templateId')::BIGINT AS key, -1 AS ord, FALSE AS deleted, item + FROM jsonb_array_elements(prior->'entries') item + UNION ALL + SELECT r.template_id, r.revision_order, r.operation_kind = 'DELETE', template_config_revision_item(r) + FROM game_design_template_config_source_revision r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY key) FILTER (WHERE NOT deleted), '[]'::JSONB) + INTO expected_items FROM final; + WITH choices AS ( + SELECT item->>'owner' AS owner, -1 AS ord, item + FROM jsonb_array_elements(prior->'ownerSourceInventoryDeclarations') item + UNION ALL + SELECT d.owner, d.revision_order, + jsonb_build_object('owner', d.owner, 'inventoryJson', d.inventory_json, + 'sourceBindingJson', source.binding_json, 'sourceBindingDigest', source.input_digest, + 'revisionOrder', d.revision_order::TEXT, 'revisionId', d.revision_id::TEXT) + FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_draft_commit source ON source.canonical_tenant_id = d.canonical_tenant_id + AND source.canonical_version_id = d.canonical_version_id + AND source.request_id = d.request_id AND source.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND d.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (owner) owner, ord, item FROM choices ORDER BY owner, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY owner), '[]'::JSONB) + INTO expected_declarations FROM final; + IF expected_items IS DISTINCT FROM snapshot->'entries' + OR expected_declarations IS DISTINCT FROM snapshot->'ownerSourceInventoryDeclarations' + OR NEW.expected_epoch IS DISTINCT FROM h.source_epoch THEN + RAISE EXCEPTION 'template config v2 application must replay exact source and declarations' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NULL AND snapshot->'entries' IS DISTINCT FROM prior->'entries') + OR (a.commit_id IS NULL AND snapshot->'ownerSourceInventoryDeclarations' IS DISTINCT FROM prior->'ownerSourceInventoryDeclarations') + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT template_config_selected_inputs(snapshot, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, snapshot) + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility 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 AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'template config v2 snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; + END IF; + WITH choices AS ( + SELECT item->>'owner' AS owner, -1::NUMERIC AS source_epoch, -1 AS ord, item + FROM jsonb_array_elements(prior->'ownerSourceInventoryDeclarations') item + UNION ALL + SELECT d.owner, owner_application.expected_epoch::NUMERIC, d.revision_order, + jsonb_build_object('owner', d.owner, 'inventoryJson', d.inventory_json, + 'sourceBindingJson', source.binding_json, 'sourceBindingDigest', source.input_digest, + 'revisionOrder', d.revision_order::TEXT, 'revisionId', d.revision_id::TEXT) + FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_draft_commit source ON source.canonical_tenant_id = d.canonical_tenant_id + AND source.canonical_version_id = d.canonical_version_id + AND source.request_id = d.request_id AND source.commit_id = d.commit_id + JOIN game_design_template_config_source_application owner_application + ON owner_application.canonical_tenant_id = d.canonical_tenant_id + AND owner_application.canonical_version_id = d.canonical_version_id + AND owner_application.request_id = d.request_id AND owner_application.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND owner_application.expected_epoch::NUMERIC < (snapshot->>'sourceEpoch')::NUMERIC + ), final AS ( + SELECT DISTINCT ON (owner) owner, source_epoch, ord, item + FROM choices ORDER BY owner, source_epoch DESC, ord DESC + ) + SELECT coalesce(jsonb_agg(item ORDER BY owner), '[]'::JSONB) INTO expected_declarations FROM final; + IF expected_declarations IS DISTINCT FROM snapshot->'ownerSourceInventoryDeclarations' THEN + RAISE EXCEPTION 'template config v2 snapshot omits or changes authored owner inventory' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION deny_template_config_owner_inventory_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER template_config_owner_inventory_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_owner_source_inventory_declaration + FOR EACH ROW EXECUTE FUNCTION guard_template_config_owner_source_inventory_declaration(); +CREATE TRIGGER template_config_owner_inventory_no_truncate + BEFORE TRUNCATE ON game_design_template_config_owner_source_inventory_declaration + FOR EACH STATEMENT EXECUTE FUNCTION deny_template_config_owner_inventory_truncate(); + +DROP TRIGGER template_config_application_guard ON game_design_template_config_source_application; +CREATE TRIGGER template_config_application_v1_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_application_v2_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' = 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source_v2(); +CREATE TRIGGER template_config_application_immutable_guard + BEFORE UPDATE OR DELETE ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); + +DROP TRIGGER template_config_snapshot_guard ON game_design_template_config_source_snapshot; +CREATE TRIGGER template_config_snapshot_v1_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_snapshot_v2_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' = 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source_v2(); +CREATE TRIGGER template_config_snapshot_immutable_guard + BEFORE UPDATE OR DELETE ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); + +CREATE TRIGGER template_config_application_v1_declaration_presence_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_v1_snapshot_declaration_presence(); +CREATE TRIGGER template_config_snapshot_v1_declaration_presence_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_v1_snapshot_declaration_presence(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1016__entity_template_config_owner_source_inventory.sql b/services/game-design-service/src/main/resources/db/migration/V1016__entity_template_config_owner_source_inventory.sql new file mode 100644 index 0000000000..8829c8380c --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1016__entity_template_config_owner_source_inventory.sql @@ -0,0 +1,238 @@ +-- Extend the typed owner declaration from Automation to the approved empty-only Entity content. +-- Existing Automation records and payloads are retained without rewriting their original bytes. +-- [jooq ignore start] +DO $$ +DECLARE owner_constraint TEXT; +BEGIN + SELECT conname INTO STRICT owner_constraint + FROM pg_constraint + WHERE conrelid = 'game_design_template_config_owner_source_inventory_declaration'::REGCLASS + AND contype = 'c' + AND pg_get_constraintdef(oid) LIKE '%AUTOMATION_SCRIPTING%'; + EXECUTE format( + 'ALTER TABLE game_design_template_config_owner_source_inventory_declaration DROP CONSTRAINT %I', + owner_constraint); +END; +$$; + +CREATE FUNCTION entity_authored_source_inventory_supported(value JSONB) RETURNS BOOLEAN AS $$ +DECLARE family_name TEXT; +BEGIN + IF jsonb_typeof(value) IS DISTINCT FROM 'object' THEN + RETURN FALSE; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value)) <> 3 THEN + RETURN FALSE; + END IF; + IF value->>'schema' IS DISTINCT FROM 'entity-authored-source-inventory/v1' + OR jsonb_typeof(value->'schema') IS DISTINCT FROM 'string' + OR value->>'equipmentApplicability' IS DISTINCT FROM 'NOT_APPLICABLE' + OR jsonb_typeof(value->'equipmentApplicability') IS DISTINCT FROM 'string' + OR jsonb_typeof(value->'families') IS DISTINCT FROM 'object' THEN + RETURN FALSE; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value->'families')) <> 23 THEN + RETURN FALSE; + END IF; + FOREACH family_name IN ARRAY ARRAY[ + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', + 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', + 'ARCHETYPE_ROOTS', + 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS', + 'BODY_LAYOUT_ROOTS', + 'CRAFTING_INGREDIENT_BINDINGS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', + 'CRAFTING_RECIPE_ROOTS', + 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', + 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', + 'EQUIPMENT_SLOT_GROUPS', + 'EQUIPMENT_SLOT_ROOTS', + 'INBOUND_LOOT_BINDINGS', + 'ITEM_TEMPLATE_ROOTS', + 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', + 'NPC_TEMPLATE_ROOTS', + 'OTHER_ACTOR_TEMPLATE_ROOTS' + ] LOOP + IF jsonb_typeof(value->'families'->family_name) IS DISTINCT FROM 'array' THEN + RETURN FALSE; + END IF; + IF jsonb_array_length(value->'families'->family_name) <> 0 THEN + RETURN FALSE; + END IF; + END LOOP; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; +-- [jooq ignore stop] + +ALTER TABLE game_design_template_config_owner_source_inventory_declaration + ADD CONSTRAINT game_design_template_config_owner_source_inventory_owner_supported_check + CHECK (owner IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT')); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_template_config_owner_source_inventory_declaration() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; c game_design_draft_commit%ROWTYPE; revision JSONB; payload JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_genesis g + WHERE g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.canonical_version_id = NEW.canonical_version_id AND g.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c 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 NOT 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 + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT 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.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template owner inventory requires active coordinator application' USING ERRCODE = '23514'; + END IF; + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF jsonb_typeof(payload) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template owner inventory requires exact supported owner declaration' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' + OR payload->>'operation' IS DISTINCT FROM 'DECLARE_OWNER_SOURCE_INVENTORY' + OR NEW.owner IS DISTINCT FROM payload->>'owner' + OR jsonb_typeof(payload->'inventory') IS DISTINCT FROM 'object' + OR NEW.inventory_json::JSONB IS DISTINCT FROM payload->'inventory' + OR NOT template_config_unique_json(NEW.inventory_json::JSON) + OR NEW.payload_json IS DISTINCT FROM revision->>'payload' + OR NEW.payload_json::JSONB IS DISTINCT FROM payload + OR NEW.owner NOT IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT') + OR (NEW.owner = 'AUTOMATION_SCRIPTING' + AND (payload->'schemaVersion' IS DISTINCT FROM '2'::JSONB + OR payload->>'owner' IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR NOT automation_authored_source_inventory_supported(NEW.inventory_json::JSONB))) + OR (NEW.owner = 'ENTITY_MANAGEMENT' + AND (payload->'schemaVersion' IS DISTINCT FROM '3'::JSONB + OR payload->>'owner' IS DISTINCT FROM 'ENTITY_MANAGEMENT' + OR NOT entity_authored_source_inventory_supported(NEW.inventory_json::JSONB))) THEN + RAISE EXCEPTION 'template owner inventory requires exact supported owner declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] + +-- Keep the deferred atomic Game Design result check, but count owner-inventory operations in their +-- own exact retained table instead of requiring a fabricated template row revision. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION verify_template_config_application_commit() RETURNS TRIGGER AS $$ +DECLARE branding_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; + declared BIGINT; retained BIGINT; declared_inventory BIGINT; retained_inventory BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_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 c 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 r 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 h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT count(*) INTO declared_inventory FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (x->>'payload')::JSONB->>'operation' = 'DECLARE_OWNER_SOURCE_INVENTORY'; + SELECT count(*) INTO retained FROM game_design_template_config_source_revision 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 count(*) INTO retained_inventory FROM game_design_template_config_owner_source_inventory_declaration + 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; + bytes := convert_to('game-design-template-config-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained + retained_inventory OR declared_inventory <> retained_inventory + OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'TEMPLATE_CONFIG_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1017__closure_qualified_selected_publication_attestation.sql b/services/game-design-service/src/main/resources/db/migration/V1017__closure_qualified_selected_publication_attestation.sql new file mode 100644 index 0000000000..d1cae029a1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1017__closure_qualified_selected_publication_attestation.sql @@ -0,0 +1,269 @@ +-- Add closure-qualified selected releases without reclassifying or rewriting retained v1/v2 rows. +-- New selected releases bind World digest schema 4; exact historical v2 evidence still parses. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + required_world_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version NOT IN ('v2', 'v3') THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + required_world_schema := CASE NEW.attestation_schema_version WHEN 'v2' THEN 3 ELSE 4 END; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'selected release requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected release has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM required_world_schema::TEXT + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'selected World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'selected release requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'selected release requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'selected release owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'selected selector differs from original APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'selected release requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',required_world_schema),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'selected release has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'selected participant differs from commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE 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 NOT IN ('v2', 'v3') 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 NOT IN ('v2', 'v3') + 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 OR REPLACE 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 NOT IN ('v2', 'v3') THEN + RAISE EXCEPTION 'terminal publication requires complete full-version selected 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; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1018__selected_inventory_closure_profile.sql b/services/game-design-service/src/main/resources/db/migration/V1018__selected_inventory_closure_profile.sql new file mode 100644 index 0000000000..b1a997384a --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1018__selected_inventory_closure_profile.sql @@ -0,0 +1,66 @@ +-- Preserve the original v1 inventory profile and admit only the explicit closure-qualified v2 +-- profile. Publication-operation bytes and historical migration definitions remain immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + profile_anchor TEXT := $anchor$ IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + profile_replacement TEXT := $replacement$ IF (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V56 selected inventory v1 profile guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + -- The paired profile guard above checks both model identifiers and graph schemas. Keep the + -- generation-rule and artifact-decision restrictions below unchanged for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, ''); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1019__selected_release_original_account_owner_schema.sql b/services/game-design-service/src/main/resources/db/migration/V1019__selected_release_original_account_owner_schema.sql new file mode 100644 index 0000000000..cb14c5dba0 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1019__selected_release_original_account_owner_schema.sql @@ -0,0 +1,23 @@ +-- Admit both canonical original Account fence versions for selected releases. +-- Keep the complete binary binding and all exact selector/readback checks unchanged. +-- [jooq ignore start] +DO $migration$ +DECLARE + evidence_function REGPROCEDURE := '"${serviceSchema}".enforce_published_world_start_location_evidence()'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1'$anchor$; + schema_replacement TEXT := $replacement$ OR (convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v1' + AND convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v2')$replacement$; +BEGIN + SELECT pg_get_functiondef(evidence_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V69 original Account schema guard'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1020__selected_full_semantic_owner_attestation.sql b/services/game-design-service/src/main/resources/db/migration/V1020__selected_full_semantic_owner_attestation.sql new file mode 100644 index 0000000000..8460300129 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1020__selected_full_semantic_owner_attestation.sql @@ -0,0 +1,273 @@ +-- Add the selected-full semantic owner profile without rewriting retained release evidence. +-- v4 binds World 4, Entity 3 and Automation 6; v1/v2/v3 retain their original bytes and owner schemas. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + required_world_schema INTEGER; + required_entity_schema INTEGER; + required_automation_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version NOT IN ('v2', 'v3', 'v4') THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + required_world_schema := CASE NEW.attestation_schema_version WHEN 'v2' THEN 3 ELSE 4 END; + required_entity_schema := CASE NEW.attestation_schema_version WHEN 'v4' THEN 3 ELSE 2 END; + required_automation_schema := CASE NEW.attestation_schema_version WHEN 'v4' THEN 6 ELSE 5 END; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'selected release requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected release has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM required_world_schema::TEXT + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'selected World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'selected release requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'selected release requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'selected release owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'selected selector differs from original APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'selected release requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',required_world_schema),('ENTITY_MANAGEMENT',required_entity_schema),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',required_automation_schema),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'selected release has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'selected participant differs from commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE 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 NOT IN ('v2', 'v3', 'v4') 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 NOT IN ('v2', 'v3', 'v4') + 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 OR REPLACE 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 NOT IN ('v2', 'v3', 'v4') THEN + RAISE EXCEPTION 'terminal publication requires complete full-version selected 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; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1021__retained_original_start_session_actor_core_projection.sql b/services/game-design-service/src/main/resources/db/migration/V1021__retained_original_start_session_actor_core_projection.sql new file mode 100644 index 0000000000..69f3f36aa4 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1021__retained_original_start_session_actor_core_projection.sql @@ -0,0 +1,387 @@ +-- Game Design retains a private, complete source binding beside the public minimal projection. +-- No old descriptor is backfilled: pre-V73 owners have no provable GD-allocated binding identity. +ALTER TABLE game_design_start_session_launch_descriptor_binding + ADD CONSTRAINT uq_gd_start_session_launch_descriptor_owner + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id, + launch_descriptor_row_id); + +CREATE TABLE game_design_start_session_authored_actor_core_projection ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(255) NOT NULL, + launch_descriptor_row_id BIGINT NOT NULL, + policy_order INTEGER NOT NULL, + binding_id UUID NOT NULL UNIQUE, + source_binding_bytes BYTEA NOT NULL, + source_binding_digest VARCHAR(71) NOT NULL, + projection_bytes BYTEA NOT NULL, + projection_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_start_session_actor_core_projection PRIMARY KEY ( + target_namespace, canonical_tenant_id, control_plane_request_id, + launch_descriptor_row_id, policy_order), + CONSTRAINT fk_gd_start_session_actor_core_projection_owner FOREIGN KEY ( + target_namespace, canonical_tenant_id, control_plane_request_id, launch_descriptor_row_id) + REFERENCES game_design_start_session_launch_descriptor_binding ( + target_namespace, canonical_tenant_id, control_plane_request_id, launch_descriptor_row_id) + ON DELETE RESTRICT, + CONSTRAINT fk_gd_start_session_actor_core_projection_descriptor FOREIGN KEY ( + launch_descriptor_row_id) REFERENCES launch_descriptor (id) ON DELETE RESTRICT, + CONSTRAINT ck_gd_start_session_actor_core_projection_shape CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND control_plane_request_id !~ '^[[:space:]]*$' + AND launch_descriptor_row_id > 0 + AND policy_order BETWEEN 0 AND 127 + AND binding_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(source_binding_bytes) BETWEEN 1 AND 16777216 + AND source_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(projection_bytes) BETWEEN 1 AND 1048576 + AND projection_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +-- Parse the same four-byte big-endian length frames used by the private Common source value. +CREATE FUNCTION gd_start_session_actor_core_source_frame_count(payload BYTEA) RETURNS INTEGER AS $$ +DECLARE offset_bytes INTEGER := 0; frame_length BIGINT; frame_count INTEGER := 0; +BEGIN + WHILE offset_bytes < octet_length(payload) LOOP + IF offset_bytes + 4 > octet_length(payload) THEN + RAISE EXCEPTION 'truncated authored actor-core source frame' USING ERRCODE = 'check_violation'; + END IF; + frame_length := get_byte(payload, offset_bytes)::BIGINT * 16777216 + + get_byte(payload, offset_bytes + 1)::BIGINT * 65536 + + get_byte(payload, offset_bytes + 2)::BIGINT * 256 + + get_byte(payload, offset_bytes + 3); + offset_bytes := offset_bytes + 4; + IF frame_length > octet_length(payload) - offset_bytes THEN + RAISE EXCEPTION 'invalid authored actor-core source frame length' USING ERRCODE = 'check_violation'; + END IF; + offset_bytes := offset_bytes + frame_length::INTEGER; + frame_count := frame_count + 1; + END LOOP; + IF offset_bytes <> octet_length(payload) THEN + RAISE EXCEPTION 'trailing authored actor-core source bytes' USING ERRCODE = 'check_violation'; + END IF; + RETURN frame_count; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION guard_gd_start_session_actor_core_projection() RETURNS trigger AS $$ +DECLARE owner game_design_start_session_launch_descriptor_binding%ROWTYPE; + descriptor launch_descriptor%ROWTYPE; + association game_design_selected_template_world_source_association%ROWTYPE; + source_operation game_design_authored_world_source_operations%ROWTYPE; + publication game_design_publication_operation%ROWTYPE; + release published_release_bundle%ROWTYPE; + commit_row game_design_draft_commit%ROWTYPE; + policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + policy_capture game_design_realm_policy_capture%ROWTYPE; + gameplay_snapshot game_design_gameplay_rule_snapshot%ROWTYPE; + private_source BYTEA; public_projection JSONB; policy_projection JSONB; + disposition_projection JSONB; feedback_projection JSONB; + disposition_binding JSONB; feedback_binding JSONB; + policy_json TEXT; disposition_json TEXT; feedback_json TEXT; expected_order INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'authored actor-core projection proofs are insert-only and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT owner + FROM game_design_start_session_launch_descriptor_binding + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND control_plane_request_id = NEW.control_plane_request_id + AND launch_descriptor_row_id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT descriptor FROM launch_descriptor WHERE id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT association + FROM game_design_selected_template_world_source_association + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id + AND template_id = owner.game_template_id; + SELECT * INTO STRICT source_operation + FROM game_design_authored_world_source_operations + WHERE operation_id = owner.source_operation_id; + SELECT * INTO STRICT publication + FROM game_design_publication_operation + WHERE publish_workflow_id = owner.publish_workflow_id; + SELECT * INTO STRICT release FROM published_release_bundle WHERE id = owner.release_bundle_id; + SELECT * INTO STRICT commit_row + FROM game_design_draft_commit + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + SELECT * INTO STRICT policy_snapshot + FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + SELECT * INTO STRICT policy_capture + FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND publish_workflow_id = owner.publish_workflow_id; + SELECT * INTO STRICT gameplay_snapshot + FROM game_design_gameplay_rule_snapshot + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + + private_source := NEW.source_binding_bytes; + IF gd_start_session_actor_core_source_frame_count(private_source) <> 45 + OR NEW.source_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(private_source), 'hex') + OR NEW.projection_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.projection_bytes), 'hex') THEN + RAISE EXCEPTION 'authored actor-core source or projection digest/frame count differs' + USING ERRCODE = 'check_violation'; + END IF; + public_projection := convert_from(NEW.projection_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(public_projection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(public_projection)) <> 16 + OR (public_projection - ARRAY['schema', 'bindingId', 'bindingDigest', 'canonicalTenantId', + 'canonicalVersionId', 'worldSourceOperationId', 'worldSourceEvidenceDigest', 'worldSlug', + 'publicationWorkflowId', 'selectedCommitId', 'selectedCommitDigest', 'policy', 'core', + 'descriptor', 'disposition', 'safeFeedback']) IS DISTINCT FROM '{}'::JSONB THEN + RAISE EXCEPTION 'authored actor-core public projection must have its closed minimal shape' + USING ERRCODE = 'check_violation'; + END IF; + + IF convert_from(published_world_selector_frame(private_source, 0), 'UTF8') + IS DISTINCT FROM 'game-design-authored-initial-actor-core-source-binding/v1' + OR convert_from(published_world_selector_frame(private_source, 1), 'UTF8') IS DISTINCT FROM '1' + OR convert_from(published_world_selector_frame(private_source, 2), 'UTF8') + IS DISTINCT FROM owner.source_operation_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 3), 'UTF8') + IS DISTINCT FROM owner.source_evidence_digest + OR convert_from(published_world_selector_frame(private_source, 4), 'UTF8') + IS DISTINCT FROM owner.world_slug + OR convert_from(published_world_selector_frame(private_source, 5), 'UTF8') + IS DISTINCT FROM owner.publish_workflow_id + OR convert_from(published_world_selector_frame(private_source, 6), 'UTF8') + IS DISTINCT FROM owner.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 7), 'UTF8') + IS DISTINCT FROM owner.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 8), 'UTF8') + IS DISTINCT FROM commit_row.game_design_version_row_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 9), 'UTF8') + IS DISTINCT FROM commit_row.game_design_version_tenant_key + OR convert_from(published_world_selector_frame(private_source, 10), 'UTF8') + IS DISTINCT FROM commit_row.source_game_row_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 11), 'UTF8') + IS DISTINCT FROM commit_row.source_game_tenant_key + OR convert_from(published_world_selector_frame(private_source, 12), 'UTF8') + IS DISTINCT FROM commit_row.source_provenance_kind + OR convert_from(published_world_selector_frame(private_source, 13), 'UTF8') + IS DISTINCT FROM owner.selected_commit_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 14), 'UTF8') + IS DISTINCT FROM commit_row.input_digest + OR published_world_selector_frame(private_source, 15) IS DISTINCT FROM convert_to(commit_row.binding_json, 'UTF8') + OR published_world_selector_frame(private_source, 16) IS DISTINCT FROM publication.request_bytes + OR published_world_selector_frame(private_source, 17) IS DISTINCT FROM publication.terminal_evidence_bytes + OR published_world_selector_frame(private_source, 18) IS DISTINCT FROM convert_to(policy_snapshot.snapshot_json, 'UTF8') + OR published_world_selector_frame(private_source, 27) IS DISTINCT FROM convert_to(gameplay_snapshot.snapshot_json, 'UTF8') + OR policy_capture.commit_id IS DISTINCT FROM owner.selected_commit_id + OR policy_capture.operation_bytes IS DISTINCT FROM publication.request_bytes + OR policy_capture.terminal_evidence_bytes IS DISTINCT FROM publication.terminal_evidence_bytes + OR policy_capture.release_content_bytes IS DISTINCT FROM publication.release_content_bytes + OR publication.outcome IS DISTINCT FROM 'PUBLISHED' + OR publication.version_id IS DISTINCT FROM commit_row.game_design_version_row_id + OR publication.tenant_id IS DISTINCT FROM commit_row.game_design_version_tenant_key + OR publication.release_content_bytes IS DISTINCT FROM publication_release_content(release) + OR publication.published_release_bundle_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(publication.release_content_bytes), 'hex') + OR release.id IS DISTINCT FROM owner.release_bundle_id + OR release.publish_workflow_id IS DISTINCT FROM owner.publish_workflow_id + OR release.version_id IS DISTINCT FROM commit_row.game_design_version_row_id + OR release.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM owner.canonical_version_id + OR association.association_digest IS DISTINCT FROM owner.association_digest + OR association.source_operation_id IS DISTINCT FROM owner.source_operation_id + OR association.source_evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR association.world_slug IS DISTINCT FROM owner.world_slug + OR association.publish_workflow_id IS DISTINCT FROM owner.publish_workflow_id + OR source_operation.target_namespace IS DISTINCT FROM owner.target_namespace + OR source_operation.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR source_operation.world_slug IS DISTINCT FROM owner.world_slug + OR source_operation.evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR descriptor.target_namespace IS DISTINCT FROM owner.target_namespace + OR descriptor.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR descriptor.control_plane_request_id IS DISTINCT FROM owner.control_plane_request_id + OR descriptor.authored_world_source_operation_id IS DISTINCT FROM owner.source_operation_id + OR descriptor.authored_world_source_evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR descriptor.world_slug IS DISTINCT FROM owner.world_slug + OR descriptor.outcome_status NOT IN ('SUCCESS', 'FAILED') + OR (descriptor.outcome_status = 'SUCCESS' AND ( + owner.runtime_surface IS DISTINCT FROM 'EMPTY_V1' + OR descriptor.release_bundle_id IS DISTINCT FROM owner.release_bundle_id + OR descriptor.version_id IS DISTINCT FROM release.version_id)) + OR (descriptor.outcome_status = 'FAILED' + AND owner.runtime_surface IS DISTINCT FROM 'UNSUPPORTED_CAPTURE_V1') THEN + RAISE EXCEPTION 'private authored actor-core proof differs from descriptor, source, association, commit, or pinned release' + USING ERRCODE = 'check_violation'; + END IF; + + policy_json := convert_from(published_world_selector_frame(private_source, 22), 'UTF8'); + disposition_json := convert_from(published_world_selector_frame(private_source, 30), 'UTF8'); + feedback_json := convert_from(published_world_selector_frame(private_source, 38), 'UTF8'); + policy_projection := public_projection->'policy'; + disposition_projection := public_projection->'disposition'; + feedback_projection := public_projection->'safeFeedback'; + disposition_binding := convert_from(published_world_selector_frame(private_source, 34), 'UTF8')::JSONB; + feedback_binding := convert_from(published_world_selector_frame(private_source, 42), 'UTF8')::JSONB; + SELECT (ordered.policy_order)::INTEGER INTO expected_order + FROM ( + SELECT policy_item->>'commitId' AS commit_id, + policy_item->>'revisionId' AS revision_id, + policy_item->>'logicalRevisionId' AS logical_revision_id, + row_number() OVER ( + ORDER BY policy_item->'policy'->>'worldSlug', policy_item->'policy'->>'realmSlug') - 1 + AS policy_order + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->'policy'->>'worldSlug' = owner.world_slug + AND policy_item->'policy'->'schemaVersion' = '3'::JSONB + AND policy_item->'policy'->>'initialActorCore' IS NOT NULL + ) ordered + WHERE ordered.commit_id = convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + AND ordered.revision_id = convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + AND ordered.logical_revision_id = convert_from(published_world_selector_frame(private_source, 21), 'UTF8'); + IF public_projection->>'schema' IS DISTINCT FROM 'game-design-authored-initial-actor-core-projection/v1' + OR public_projection->>'bindingId' IS DISTINCT FROM NEW.binding_id::TEXT + OR public_projection->>'bindingDigest' IS DISTINCT FROM NEW.source_binding_digest + OR public_projection->>'canonicalTenantId' IS DISTINCT FROM owner.canonical_tenant_id::TEXT + OR public_projection->>'canonicalVersionId' IS DISTINCT FROM owner.canonical_version_id::TEXT + OR public_projection->>'worldSourceOperationId' IS DISTINCT FROM owner.source_operation_id::TEXT + OR public_projection->>'worldSourceEvidenceDigest' IS DISTINCT FROM owner.source_evidence_digest + OR public_projection->>'worldSlug' IS DISTINCT FROM owner.world_slug + OR public_projection->>'publicationWorkflowId' IS DISTINCT FROM owner.publish_workflow_id + OR public_projection->>'selectedCommitId' IS DISTINCT FROM owner.selected_commit_id::TEXT + OR public_projection->>'selectedCommitDigest' IS DISTINCT FROM commit_row.input_digest + OR (SELECT count(*) FROM jsonb_object_keys(policy_projection)) <> 5 + OR (policy_projection - ARRAY['commitId', 'revisionId', 'logicalRevisionId', 'canonicalPolicyJson', 'contentDigest']) + IS DISTINCT FROM '{}'::JSONB + OR policy_projection->>'commitId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + OR policy_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + OR policy_projection->>'logicalRevisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 21), 'UTF8') + OR policy_projection->>'canonicalPolicyJson' IS DISTINCT FROM policy_json + OR policy_projection->>'contentDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(policy_json, 'UTF8')), 'hex') + OR expected_order IS DISTINCT FROM NEW.policy_order + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->>'commitId' = convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + AND policy_item->>'revisionId' = convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + AND policy_item->>'logicalRevisionId' = convert_from(published_world_selector_frame(private_source, 21), 'UTF8') + AND policy_item->'policy' = policy_json::JSONB) + OR (public_projection->'core' - ARRAY['canonicalJson']) IS DISTINCT FROM '{}'::JSONB + OR public_projection->'core'->>'canonicalJson' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 26), 'UTF8') + OR (public_projection->'descriptor' - ARRAY['canonicalJson', 'digest']) IS DISTINCT FROM '{}'::JSONB + OR public_projection->'descriptor'->>'canonicalJson' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 25), 'UTF8') + OR public_projection->'descriptor'->>'digest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 25)), 'hex') + OR (SELECT count(*) FROM jsonb_object_keys(disposition_projection)) <> 7 + OR (disposition_projection - ARRAY['key', 'definitionJson', 'definitionDigest', 'sourceCommitId', + 'sourceCommitDigest', 'revisionId', 'revisionOrder']) IS DISTINCT FROM '{}'::JSONB + OR disposition_projection->>'key' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 29), 'UTF8') + OR disposition_projection->>'definitionJson' IS DISTINCT FROM disposition_json + OR convert_from(published_world_selector_frame(private_source, 31), 'UTF8') IS DISTINCT FROM 'DISPOSITIONS' + OR published_world_selector_frame(private_source, 32) IS DISTINCT FROM + published_world_selector_frame(private_source, 30) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(gameplay_snapshot.snapshot_json::JSONB->'entries') rule_entry + WHERE rule_entry = jsonb_build_object( + 'family', 'DISPOSITIONS', + 'definitionJson', convert_from(published_world_selector_frame(private_source, 32), 'UTF8'), + 'sourceBindingJson', convert_from(published_world_selector_frame(private_source, 34), 'UTF8'), + 'sourceBindingDigest', convert_from(published_world_selector_frame(private_source, 33), 'UTF8'), + 'revisionOrder', convert_from(published_world_selector_frame(private_source, 35), 'UTF8'), + 'revisionId', convert_from(published_world_selector_frame(private_source, 36), 'UTF8'))) + OR disposition_projection->>'definitionDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(disposition_json, 'UTF8')), 'hex') + OR disposition_projection->>'sourceCommitId' IS DISTINCT FROM disposition_binding->>'commitId' + OR disposition_projection->>'sourceCommitDigest' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 33), 'UTF8') + OR disposition_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 36), 'UTF8') + OR disposition_projection->>'revisionOrder' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 35), 'UTF8') + OR disposition_projection->>'sourceCommitDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 34)), 'hex') + OR (SELECT count(*) FROM jsonb_object_keys(feedback_projection)) <> 7 + OR (feedback_projection - ARRAY['key', 'definitionJson', 'definitionDigest', 'sourceCommitId', + 'sourceCommitDigest', 'revisionId', 'revisionOrder']) IS DISTINCT FROM '{}'::JSONB + OR feedback_projection->>'key' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 37), 'UTF8') + OR feedback_projection->>'definitionJson' IS DISTINCT FROM feedback_json + OR convert_from(published_world_selector_frame(private_source, 39), 'UTF8') IS DISTINCT FROM 'FEEDBACK' + OR published_world_selector_frame(private_source, 40) IS DISTINCT FROM + published_world_selector_frame(private_source, 38) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(gameplay_snapshot.snapshot_json::JSONB->'entries') rule_entry + WHERE rule_entry = jsonb_build_object( + 'family', 'FEEDBACK', + 'definitionJson', convert_from(published_world_selector_frame(private_source, 40), 'UTF8'), + 'sourceBindingJson', convert_from(published_world_selector_frame(private_source, 42), 'UTF8'), + 'sourceBindingDigest', convert_from(published_world_selector_frame(private_source, 41), 'UTF8'), + 'revisionOrder', convert_from(published_world_selector_frame(private_source, 43), 'UTF8'), + 'revisionId', convert_from(published_world_selector_frame(private_source, 44), 'UTF8'))) + OR feedback_projection->>'definitionDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(feedback_json, 'UTF8')), 'hex') + OR feedback_projection->>'sourceCommitId' IS DISTINCT FROM feedback_binding->>'commitId' + OR feedback_projection->>'sourceCommitDigest' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 41), 'UTF8') + OR feedback_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 44), 'UTF8') + OR feedback_projection->>'revisionOrder' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 43), 'UTF8') + OR feedback_projection->>'sourceCommitDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 42)), 'hex') THEN + RAISE EXCEPTION 'public actor-core projection differs from exact source or leaks an open proof shape' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_gd_start_session_actor_core_projection_set() RETURNS trigger AS $$ +DECLARE policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + expected_count BIGINT; retained_count BIGINT; +BEGIN + 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.selected_commit_id; + SELECT count(*) INTO expected_count + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->'policy'->>'worldSlug' = NEW.world_slug + AND policy_item->'policy'->'schemaVersion' = '3'::JSONB + AND policy_item->'policy'->>'initialActorCore' IS NOT NULL; + SELECT count(*) INTO retained_count + FROM game_design_start_session_authored_actor_core_projection proof + WHERE proof.target_namespace = NEW.target_namespace + AND proof.canonical_tenant_id = NEW.canonical_tenant_id + AND proof.control_plane_request_id = NEW.control_plane_request_id + AND proof.launch_descriptor_row_id = NEW.launch_descriptor_row_id; + IF expected_count IS DISTINCT FROM retained_count THEN + RAISE EXCEPTION 'new descriptor owner must retain every applicable authored actor-core proof in order' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_actor_core_projection + BEFORE INSERT OR UPDATE OR DELETE ON game_design_start_session_authored_actor_core_projection + FOR EACH ROW EXECUTE FUNCTION guard_gd_start_session_actor_core_projection(); + +CREATE FUNCTION reject_gd_start_session_actor_core_projection_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'authored actor-core projection proofs are retained' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_actor_core_projection_no_truncate + BEFORE TRUNCATE ON game_design_start_session_authored_actor_core_projection + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_start_session_actor_core_projection_truncate(); + +CREATE CONSTRAINT TRIGGER trg_gd_start_session_actor_core_projection_complete_owner_set + AFTER INSERT ON game_design_start_session_launch_descriptor_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_gd_start_session_actor_core_projection_set(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1022__restore_selected_release_original_account_owner_schema.sql b/services/game-design-service/src/main/resources/db/migration/V1022__restore_selected_release_original_account_owner_schema.sql new file mode 100644 index 0000000000..61d8ec885b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1022__restore_selected_release_original_account_owner_schema.sql @@ -0,0 +1,23 @@ +-- Restore the V71 Account schema predicate after V72 replaces the full release guard. +-- Keep every exact owner-byte, selector, applied-result, receipt and participant check unchanged. +-- [jooq ignore start] +DO $migration$ +DECLARE + evidence_function REGPROCEDURE := '"${serviceSchema}".enforce_published_world_start_location_evidence()'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1'$anchor$; + schema_replacement TEXT := $replacement$ OR (convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v1' + AND convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v2')$replacement$; +BEGIN + SELECT pg_get_functiondef(evidence_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V72 selected-release Account schema guard'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1023__selected_export_artifact_projection.sql b/services/game-design-service/src/main/resources/db/migration/V1023__selected_export_artifact_projection.sql new file mode 100644 index 0000000000..3a569b341c --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1023__selected_export_artifact_projection.sql @@ -0,0 +1,108 @@ +-- Keep ordinary snapshot/origin evidence separate from exact selected-inventory candidates. +-- No retained candidate, source row, original operation or delivery origin is backfilled. +ALTER TABLE version_asset_export_candidate + ADD CONSTRAINT uq_selected_export_candidate_request + UNIQUE (tenant_id, version_id, request_digest); + +ALTER TABLE version_asset_artifact + ADD COLUMN selected_candidate_version_id BIGINT, + ADD COLUMN selected_candidate_request_digest VARCHAR(64), + ADD CONSTRAINT fk_asset_selected_export_candidate + FOREIGN KEY (tenant_id, selected_candidate_version_id, selected_candidate_request_digest) + REFERENCES version_asset_export_candidate (tenant_id, version_id, request_digest); + +ALTER TABLE version_asset_artifact + DROP CONSTRAINT chk_asset_export_candidate_evidence; + +ALTER TABLE version_asset_artifact + ADD CONSTRAINT chk_asset_export_candidate_evidence CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL + AND published_object_proofs_json IS NULL AND candidate_snapshot_version_id IS NULL + AND selected_candidate_version_id IS NULL AND selected_candidate_request_digest IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL + AND published_object_proofs_json IS NOT NULL AND manifest_hash IS NOT NULL + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$' + AND ( + (candidate_snapshot_version_id IS NOT NULL + AND candidate_snapshot_version_id = version_id + AND selected_candidate_version_id IS NULL + AND selected_candidate_request_digest IS NULL) + OR (candidate_snapshot_version_id IS NULL AND candidate_public_base_url IS NULL + AND selected_candidate_version_id IS NOT NULL + AND selected_candidate_version_id = version_id + AND selected_candidate_request_digest IS NOT NULL + AND selected_candidate_request_digest ~ '^[0-9a-f]{64}$') + )) + ); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_asset_export_candidate_evidence() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.manifest_schema_version IS NOT NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN OLD; + END IF; + + IF NEW.manifest_schema_version IS NOT NULL + AND NEW.selected_candidate_version_id IS NULL + AND (TG_OP = 'INSERT' OR OLD.manifest_schema_version IS NULL) + AND NEW.candidate_public_base_url IS NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_ORIGIN_REQUIRED'; + END IF; + + IF NEW.selected_candidate_version_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 + FROM version_asset_export_candidate c + JOIN version v ON v.tenant_id = c.tenant_id AND v.id = c.version_id + WHERE c.tenant_id = NEW.tenant_id + AND c.version_id = NEW.selected_candidate_version_id + AND c.request_digest = NEW.selected_candidate_request_digest + AND c.workflow_id = NEW.last_workflow_id + AND c.canonical_tenant_id = v.canonical_tenant_id + AND c.canonical_version_id = v.canonical_version_id + AND v.version_number = NEW.exported_version_number + AND c.manifest_schema_version = NEW.manifest_schema_version + AND c.manifest_hash = NEW.manifest_hash + AND c.manifest_hash = 'sha256:' || encode(sha256(c.manifest_bytes), 'hex') + AND c.artifact_digests_json::JSONB = NEW.artifact_digests_json::JSONB + AND c.required_usage_keys_json::JSONB = NEW.exported_manifest_asset_keys_json::JSONB + AND NEW.published_object_proofs_json::JSONB = ( + SELECT jsonb_agg( + jsonb_build_object('immutableObjectKey', proof.object_key, + 'contentDigest', proof.content_digest) + ORDER BY proof.object_key COLLATE "C", proof.content_digest COLLATE "C") + FROM ( + SELECT artifact->>'immutableObjectKey' AS object_key, + artifact->>'contentDigest' AS content_digest + FROM jsonb_array_elements(c.artifact_digests_json::JSONB) AS artifacts(artifact) + UNION + SELECT 'manifests/sha256/' || substring(c.manifest_hash FROM 8), c.manifest_hash + ) proof + ) + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' AND OLD.manifest_schema_version IS NOT NULL AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.exported_version_number IS DISTINCT FROM OLD.exported_version_number + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.manifest_schema_version IS DISTINCT FROM OLD.manifest_schema_version + OR NEW.artifact_digests_json IS DISTINCT FROM OLD.artifact_digests_json + OR NEW.published_object_proofs_json IS DISTINCT FROM OLD.published_object_proofs_json + OR NEW.candidate_snapshot_version_id IS DISTINCT FROM OLD.candidate_snapshot_version_id + OR NEW.candidate_public_base_url IS DISTINCT FROM OLD.candidate_public_base_url + OR NEW.selected_candidate_version_id IS DISTINCT FROM OLD.selected_candidate_version_id + OR NEW.selected_candidate_request_digest IS DISTINCT FROM OLD.selected_candidate_request_digest + OR NEW.exported_manifest_asset_keys_json IS DISTINCT FROM OLD.exported_manifest_asset_keys_json + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql b/services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql new file mode 100644 index 0000000000..7797f139c6 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql @@ -0,0 +1,184 @@ +-- Fresh reviews bind the actual ordinary asset owner baseline alongside policy and command. +-- Original v1 review rows and their exact evidence bytes remain immutable; no history is backfilled. +-- PostgreSQL owns the original unnamed CHECK name; jOOQ's H2 interpreter assigns another. +-- This changes checks, not generated columns; native migration proof validates the exact guard. +-- [jooq ignore start] +ALTER TABLE game_design_reviewed_draft_base + DROP CONSTRAINT game_design_reviewed_draft_base_evidence_schema_check; +ALTER TABLE game_design_reviewed_draft_base + ADD CONSTRAINT game_design_reviewed_draft_base_evidence_schema_check + CHECK (evidence_schema IN ('game-design-reviewed-draft-base/v1', 'game-design-reviewed-draft-base/v2')); + +CREATE OR REPLACE 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; + asset_genesis game_design_asset_source_genesis%ROWTYPE; + asset_genesis_bytes BYTEA; + 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; + asset_snapshot game_design_asset_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; + IF NEW.evidence_schema IS DISTINCT FROM 'game-design-reviewed-draft-base/v2' THEN + RAISE EXCEPTION 'Fresh reviewed base requires complete asset-bound v2 owner evidence'; + 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; + SELECT * INTO STRICT asset_genesis FROM game_design_asset_source_genesis + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND version_id = claim.game_design_version_row_id; + IF asset_genesis.creation_transaction_id IS DISTINCT FROM witness.creation_transaction_id + OR asset_genesis.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', claim.canonical_tenant_id::TEXT, + 'canonicalVersionId', claim.canonical_version_id::TEXT, + 'gameDesignVersionRowId', claim.game_design_version_row_id, + 'gameDesignVersionTenantKey', claim.game_design_version_tenant_key, + 'sourceGameRowId', claim.source_game_row_id, + 'sourceGameTenantKey', claim.source_game_tenant_key, + 'sourceProvenanceKind', claim.source_provenance_kind) THEN + RAISE EXCEPTION 'Reviewed asset genesis must retain the exact target and original insertion witness'; + END IF; + asset_genesis_bytes := game_design_reviewed_base_frame('game-design-ordinary-asset-source-genesis/v1'::TEXT) + || game_design_reviewed_base_frame(asset_genesis.target_json) + || game_design_reviewed_base_frame(asset_genesis.receipt_id::TEXT) + || game_design_reviewed_base_frame(asset_genesis.creation_transaction_id); + source_bytes := game_design_reviewed_base_frame('shared-policy-command-asset-genesis/v2'::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) + || game_design_reviewed_base_frame(asset_genesis_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; + SELECT * INTO STRICT asset_snapshot FROM game_design_asset_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 asset_snapshot.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM base.binding_json + OR asset_snapshot.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM base.input_digest + OR asset_snapshot.snapshot_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(asset_snapshot.snapshot_json, 'UTF8')), 'hex') + 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-asset-base/v2'::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(convert_to(asset_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; + +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedAssetSourceOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedAssetSourceOwnerSetup.java new file mode 100644 index 0000000000..9b1cd34b70 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedAssetSourceOwnerSetup.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.util.List; +import java.util.UUID; +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.AssetSource; +import net.firedevops.firemud.common.gamedesign.AssetSource.Requiredness; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; + +/** Isolated test producer for an actual reviewed ordinary asset source commit and owner fence. */ +public final class IsolatedAssetSourceOwnerSetup { + private IsolatedAssetSourceOwnerSetup() {} + + /** + * Call inside the fixture's writable READ COMMITTED transaction after fresh Version insertion. + */ + public static DraftCommitBinding upsert( + DSLContext dsl, TargetProof target, long assetId, String usageKey) { + var sources = new GameDesignSourceRepository(dsl); + var genesis = sources.readGenesis(target).orElseThrow(); + String base = "genesis:" + genesis.policy().receiptId(); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + base, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload( + Long.toString(assetId), usageKey, Requiredness.REQUIRED))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + sources.claimReviewed( + binding, + new GameDesignReviewedBaseRepository(dsl) + .resolve(target, DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var result = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(result.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + return binding; + } +} 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 index f67705e9f7..b135d2b0bd 100644 --- 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.draft; import java.math.BigInteger; +import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -10,6 +11,7 @@ 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.gamedesign.AssetSource; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -69,6 +71,17 @@ public static GameDesignPublicationOperation retain( return retain(dsl, target, draftEpoch, notes, false); } + /** + * Explicit pre-V56 owner history fixture. The real coordinator, selection, attempt and operation + * writes retain original v1 framing; enabled storage guards reject this method after V56. + * Stipulated upstream values never provide historical inventory or fresh v2 authority. + */ + public static GameDesignPublicationOperation retainHistoricalV1PreV56( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain( + dsl, target, draftEpoch, "ISOLATED retained pre-V56 owner history", false, null, true); + } + /** 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 { @@ -106,13 +119,33 @@ public static GameDesignPublicationOperation retainSourceBacked( public static GameDesignPublicationOperation retainFrozenSourceBacked( DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) throws Exception { - String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target); + return retainFrozenSourceBacked(dsl, target, draftEpoch, notes, List.of()); + } + + /** Actual owner rows must already exist before the reviewed policy/asset source commit. */ + public static GameDesignPublicationOperation retainFrozenSourceBacked( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + List ordinaryAssets) + throws Exception { + String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target, ordinaryAssets); GameDesignPublicationOperation operation = retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit); new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation); return operation; } + /** Fixture input from an actual same-tenant game_assets row, not publication authority. */ + public record OrdinaryAsset(long assetRowId, String usageKey) { + public OrdinaryAsset { + if (assetRowId <= 0 || usageKey == null || usageKey.isBlank()) { + throw new IllegalArgumentException("Exact ordinary asset row and usage key are required"); + } + } + } + private static GameDesignPublicationOperation retain( DSLContext dsl, DraftCommitBinding.TargetProof target, @@ -131,6 +164,18 @@ private static GameDesignPublicationOperation retain( boolean captureSources, String sourceBaseReference) throws Exception { + return retain(dsl, target, draftEpoch, notes, captureSources, sourceBaseReference, false); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + String sourceBaseReference, + boolean historicalV1) + throws Exception { var sources = new GameDesignSourceRepository(dsl); var reviewed = new GameDesignReviewedBaseRepository(dsl); var evidence = @@ -184,6 +229,7 @@ private static GameDesignPublicationOperation retain( var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome)); if (captureSources) { coordinator.advanceSourceVisibilityFence(draft, proof); + sources.captureSynchronized(draft); } else { coordinator.advanceVisibilityFence(draft, proof); } @@ -201,11 +247,14 @@ private static GameDesignPublicationOperation retain( draft.commitId(), draft.digest())) .selection(); + var selectedBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); var operation = - IsolatedPublicationOperationFixtures.forSelection( - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - seed.world()); + historicalV1 + ? IsolatedPublicationOperationFixtures.historicalV1ForSelection( + selectedBinding, seed.world()) + : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seed.world()); var attempt = new PublishAttempt(); attempt.setTenantId(target.gameDesignVersionTenantKey()); attempt.setPublishWorkflowId(operation.workflowId()); @@ -227,36 +276,56 @@ private static GameDesignPublicationOperation retain( } private static String retainPublicProductionPolicy( - DSLContext dsl, DraftCommitBinding.TargetProof target) { + DSLContext dsl, DraftCommitBinding.TargetProof target, List ordinaryAssets) { var sources = new GameDesignSourceRepository(dsl); var genesis = sources.readGenesis(target).orElseThrow(); String baseReference = "genesis:" + genesis.policy().receiptId(); + var revisions = new ArrayList(); + revisions.add( + 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\"}}")); + var affected = new ArrayList(); + affected.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0")); + for (OrdinaryAsset asset : List.copyOf(ordinaryAssets)) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload( + Long.toString(asset.assetRowId()), + asset.usageKey(), + AssetSource.Requiredness.REQUIRED))); + } + if (!ordinaryAssets.isEmpty()) { + affected.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0")); + } 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"))); + target, UUID.randomUUID(), UUID.randomUUID(), baseReference, revisions, affected); var reviewed = new GameDesignReviewedBaseRepository(dsl); sources.claimReviewed( binding, reviewed.resolve(target, DraftBaseReference.parse(baseReference))); @@ -268,6 +337,7 @@ private static String retainPublicProductionPolicy( binding, new DraftCommitCoordinatorRepository.CoordinatorProof( binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); coordinator.releaseApplicationSlot(binding); return binding.commitId().toString(); } 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 index 9457f43972..0554126103 100644 --- 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.publication; +import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; @@ -15,6 +16,7 @@ import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; import tools.jackson.databind.ObjectMapper; /** @@ -113,6 +115,22 @@ private static GameDesignPublicationOperation fresh( public static GameDesignPublicationOperation forSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + return selection(selected, seed, false); + } + + /** + * Explicit pre-v2 fixture preimage for retained-schema tests only. Decoding these original three + * frames preserves history; it cannot provide complete inventory or fresh v2 authority. + */ + public static GameDesignPublicationOperation historicalV1ForSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + return selection(selected, seed, true); + } + + private static GameDesignPublicationOperation selection( + AuthoredDraftPublishSelectionBinding selected, + WorldPublishedStartLocationEvidence seed, + boolean historicalV1) { var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var target = selected.target(); @@ -168,6 +186,14 @@ public static GameDesignPublicationOperation forSelection( seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), seed.appliedResultBytes()); - return new GameDesignPublicationOperation(account, world); + if (historicalV1) { + var original = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(original, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(original, account.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(original, world.canonicalBytes()); + return GameDesignPublicationOperation.fromStored(original.toByteArray()); + } + return new GameDesignPublicationOperation( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); } } 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 index d9094132da..cd257cf563 100644 --- 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 @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.security.MessageDigest; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.UUID; @@ -13,6 +15,7 @@ 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.common.gamedesign.AssetSource; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; @@ -46,11 +49,107 @@ class GameDesignSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void ordinaryAssetSourceProjectsInheritedAndDeletedReferencesThroughCoordinatorFence() + throws Exception { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + assertThat(genesis.asset().receiptId()).isNotEqualTo(genesis.policy().receiptId()); + assertThat(genesis.asset().target()).isEqualTo(fixture.target()); + assertThat(genesis.asset().creationTransactionId()) + .isEqualTo(genesis.policy().creationTransactionId()); + long assetId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " + + "VALUES (?, 'logo.bin', 'application/octet-stream', ?) RETURNING id", + fixture.target().gameDesignVersionTenantKey(), + new byte[] {0, 1, (byte) 0xff}) + .get(0, Long.class); + DraftCommitBinding upsert = + assetBinding( + fixture.target(), + "genesis:" + genesis.policy().receiptId(), + "0", + AssetSource.upsertPayload( + Long.toString(assetId), "logo.bin", AssetSource.Requiredness.REQUIRED)); + var applied = apply(fixture, upsert); + synchronize(fixture, upsert, applied); + var selected = + fixture.sources().readSynchronized(fixture.target(), upsert.commitId()).orElseThrow(); + assertThat(selected.asset().items()).hasSize(1); + var selectedAsset = selected.asset().items().getFirst(); + assertThat(selectedAsset.reference().usageKey()).isEqualTo("logo.bin"); + assertThat(selectedAsset.reference().assetRowId()).isEqualTo(Long.toString(assetId)); + assertThat(selectedAsset.byteSize()).isEqualTo(3); + assertThat(selectedAsset.contentType()).isEqualTo("application/octet-stream"); + assertThat(selectedAsset.contentDigest()) + .isEqualTo( + "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(new byte[] {0, 1, (byte) 0xff}))); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isEqualTo(1); + + DraftCommitBinding command = + binding(fixture.target(), upsert.commitId().toString(), null, "0", null, false); + var commandApplied = apply(fixture, command); + synchronize(fixture, command, commandApplied); + var inherited = + fixture.sources().readSynchronized(fixture.target(), command.commitId()).orElseThrow(); + assertThat(inherited.asset().items()).containsExactlyElementsOf(selected.asset().items()); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isEqualTo(1); + + DraftCommitBinding staleDelete = + assetBinding( + fixture.target(), + command.commitId().toString(), + "0", + AssetSource.deletePayload("logo.bin")); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + start(fixture, staleDelete); + return fixture.sources().apply(staleDelete); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_SOURCE_EPOCH_CONFLICT"); + assertThat(fixture.coordinator().readApplicationSlot(fixture.target())).isEmpty(); + assertThat( + fixture.sources().readSynchronized(fixture.target(), command.commitId()).orElseThrow()) + .isEqualTo(inherited); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isEqualTo(1); + DraftCommitBinding delete = + assetBinding( + fixture.target(), + command.commitId().toString(), + "1", + AssetSource.deletePayload("logo.bin")); + var deleted = apply(fixture, delete); + synchronize(fixture, delete, deleted); + assertThat( + fixture + .sources() + .readSynchronized(fixture.target(), delete.commitId()) + .orElseThrow() + .asset() + .items()) + .isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isZero(); + } + @Test void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() { Fixture fixture = fixture(); var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); + assertThat(genesis.asset().receiptId()).isNotEqualTo(genesis.policy().receiptId()); + assertThat(genesis.asset().target()).isEqualTo(fixture.target()); + assertThat(genesis.asset().creationTransactionId()) + .isEqualTo(genesis.policy().creationTransactionId()); assertThat(genesis.policy().creationTransactionId()) .isEqualTo(genesis.command().creationTransactionId()); assertThat(fixture.tx(() -> fixture.sources().enrollFreshDraft(fixture.target()))) @@ -66,6 +165,7 @@ void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() fixture.sources().readSynchronized(fixture.target(), policy.commitId()).orElseThrow(); assertThat(policySnapshot.policy().policies()).hasSize(1); assertThat(policySnapshot.command().definitions()).isEmpty(); + assertThat(policySnapshot.asset().items()).isEmpty(); DraftCommitBinding command = binding(fixture.target(), policy.commitId().toString(), null, "0", null, false); @@ -76,6 +176,7 @@ void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() assertThat(commandSnapshot.policy().policies()) .containsExactlyElementsOf(policySnapshot.policy().policies()); assertThat(commandSnapshot.command().definitions()).hasSize(1); + assertThat(commandSnapshot.asset().items()).isEmpty(); assertThat(commandResult.ownerOutcome().appliedEpochs()) .containsExactly(commandResult.command().orElseThrow().commandAppliedEpoch()); @@ -96,6 +197,7 @@ void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() fixture.sources().readSynchronized(fixture.target(), mixed.commitId()).orElseThrow(); assertThat(mixedSnapshot.policy().sourceEpoch()).isEqualTo("2"); assertThat(mixedSnapshot.command().sourceEpoch()).isEqualTo("2"); + assertThat(mixedSnapshot.asset().items()).isEmpty(); assertThat(mixedSnapshot.command().definitions().getFirst().sourceCommitId()) .isEqualTo(mixed.commitId()); assertThat(fixture.tx(() -> fixture.sources().captureSynchronized(mixed))) @@ -472,6 +574,25 @@ private static DraftCommitBinding binding( target, UUID.randomUUID(), UUID.randomUUID(), base, revisions, scopes); } + private static DraftCommitBinding assetBinding( + TargetProof target, String base, String expectedEpoch, String payload) { + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + base, + List.of( + new RevisionPayload("0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + expectedEpoch))); + } + private static String withRawRequiredOwners(String canonicalJson, String requiredOwnerJson) { String validRequiredOwners = "\"requiredOwners\":[\"GAME_DESIGN_CONTROL_PLANE\"]"; assertThat(canonicalJson).contains(validRequiredOwners); 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 index 5280ade5c9..7d9706c214 100644 --- 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 @@ -60,8 +60,12 @@ void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { var fixture = freshFixture(); var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); + assertThat(genesis.asset().receiptId()).isNotEqualTo(genesis.policy().receiptId()); + assertThat(genesis.asset().target()).isEqualTo(fixture.target()); assertThat(genesis.policy().creationTransactionId()) .isEqualTo(genesis.command().creationTransactionId()); + assertThat(genesis.asset().creationTransactionId()) + .isEqualTo(genesis.policy().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(); @@ -78,6 +82,15 @@ void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { synchronize(fixture, first, applied); assertThat(fixture.reads().readSnapshot(fixture.target(), first.commitId()).orElseThrow()) .isEqualTo(applied.snapshot()); + assertThat( + fixture + .sources() + .readSynchronized(fixture.target(), first.commitId()) + .orElseThrow() + .asset() + .items()) + .isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isZero(); } @Test diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java new file mode 100644 index 0000000000..dc483b0092 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -0,0 +1,1320 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +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; +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.common.world.WorldDraftStartLocationEvidence; +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.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +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.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.junit.jupiter.api.io.TempDir; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +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; + +/** + * Native storage upgrade proof preserving retained v1 and mandatory complete v2 decoding. Account, + * World APPLIED/freeze and complete inventory input are explicitly stipulated external test data. + * Real Game Design repositories write the Version, coordinator, selection and attempt; all database + * guards remain enabled. This does not prove authenticated production or publication activation. + * Qualification requires physical Docker execution with zero skips; unavailable Docker is unrun + * proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class SelectedPublicationStorageUpgradePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String V2 = "game-design-publication-operation/v2"; + + // Exact installed parent artifacts at Entity source 9526190049a86feef40cd616ec7b5eb931247e8b. + private static final Set PARENT_MIGRATION_SCRIPTS = + Set.of( + "V10__version_asset_artifact.sql", + "V11__launch_descriptor_framework.sql", + "V12__version_asset_purge_workflow.sql", + "V13__version_state_control_plane.sql", + "V14__recorded_participant_digest.sql", + "V15__template_remap_sets.sql", + "V16__version_asset_artifact_export_version.sql", + "V17__revision_version_scope.sql", + "V18__published_plugin_versions.sql", + "V19__plugin_publication_policy_metadata.sql", + "V1__init.sql", + "V20__plugin_publication_status_reason.sql", + "V21__plugin_version_status_events.sql", + "V22__game_authored_help_topics.sql", + "V23__published_command_definitions.sql", + "V24__publication_workflow_identity_capacity.sql", + "V25__persist_script_patch_attempt_scope.sql", + "V26__bind_participant_digest_patch_scope.sql", + "V27__enforce_script_patch_artifact_identity.sql", + "V28__quarantine_legacy_unattested_full_versions.sql", + "V29__canonical_game_tenant_identity.sql", + "V2__game_templates.sql", + "V30__game_tenant_creation_operations.sql", + "V34.1__authored_world_source_operations.sql", + "V35.1__canonical_version_identity.sql", + "V35.2__canonical_release_version_identity.sql", + "V35__authored_source_launch_descriptor_binding.sql", + "V36__persist_opaque_published_release_bundle_reference.sql", + "V37__version_asset_export_snapshot.sql", + "V38__published_asset_digest_evidence.sql", + "V39__publication_evidence_text_storage.sql", + "V3__game_assets.sql", + "V41__world_authored_source_delivery.sql", + "V42__enforce_version_asset_export_source_digest.sql", + "V49.1__selected_world_release_participant_schema.sql", + "V49__published_world_start_location_evidence.sql", + "V4__add_tenant_indexes.sql", + "V50.10__immutable_command_source.sql", + "V50.11__immutable_reviewed_draft_base.sql", + "V50.12__realm_policy_source_head_transition_guard.sql", + "V50.13__stable_publication_release_row_evidence.sql", + "V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql", + "V50.15__draft_commit_required_owner_guards.sql", + "V50.16__reviewed_source_application_guards.sql", + "V50.1__durable_draft_commit_coordination.sql", + "V50.2__authored_draft_publish_selection.sql", + "V50.3__authored_draft_publish_request_identity.sql", + "V50.4__selected_publish_attempt_digest_capacity.sql", + "V50.5__game_design_draft_terminal_outcomes.sql", + "V50.6__publication_operation_terminal_seal.sql", + "V50.7__publication_terminal_content_and_epoch.sql", + "V50.8__immutable_realm_policy_source.sql", + "V50.9__sealed_realm_policy_publication_evidence.sql", + "V50__freeze_asset_export_candidate_public_origin.sql", + "V5__update_version_table.sql", + "V6__game_settings_overrides.sql", + "V7__enforce_unique_version_numbers.sql", + "V8__published_release_bundle.sql", + "V9__publish_attempt_framework.sql", + "V1000__create_saga_schema.sql", + "V1001__saga_instance_table.sql", + "V1002__saga_step_table.sql"); + + @Test + void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGuards() { + String schema = "gd_storage_fresh_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + flyway(source, schema, null).migrate(); + flyway(source, schema, null).validate(); + var dsl = DSL.using(source, SQLDialect.POSTGRES); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(84L); + assertThat( + dsl.fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1024); + assertEnabledGuards(dsl, schema); + } + + @Test + void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageTail( + @TempDir Path parentMigrations) throws Exception { + var fixture = fixture(true); + var resources = + new PathMatchingResourcePatternResolver().getResources("classpath*:db/migration/**/*.sql"); + int copied = 0; + for (var resource : resources) { + String filename = java.util.Objects.requireNonNull(resource.getFilename()); + if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; + try (var input = resource.getInputStream()) { + Files.copy(input, parentMigrations.resolve(filename)); + } + copied++; + } + assertThat(copied).isEqualTo(62); + flyway(fixture.source(), fixture.schema(), null, "filesystem:" + parentMigrations).migrate(); + var history = + fixture + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + assertThat(history).hasSize(62); + var rows = retainedRows(fixture); + + // The service's actual startup locations and default ordering must upgrade this parent. + flyway(fixture.source(), fixture.schema(), null).migrate(); + flyway(fixture.source(), fixture.schema(), null).validate(); + + assertThat( + fixture + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND installed_rank <= 62 ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(84L); + assertThat(retainedRows(fixture)).isEqualTo(rows); + assertEnabledGuards(fixture); + } + + @Test + void fullStorageUpgradeRetainsParentV1RowsBytesChecksumsAndOwnerReads() throws Exception { + var fixture = fixture(true); + var operation = fixture.operation(); + byte[] original = operation.canonicalBytes(); + new DraftAuthorizationFenceBinding.FrameReader(original) + .expect("game-design-publication-operation/v1"); + var rows = retainedRows(fixture); + var migrationHistory = predecessorChecksums(fixture); + assertThat(migrationHistory).hasSize(59); + var beforeRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThatThrownBy(operation::inventory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + + upgrade(fixture); + + assertThat(predecessorChecksums(fixture)).isEqualTo(migrationHistory); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(84L); + assertThat(retainedRows(fixture)).isEqualTo(rows); + assertThat(GameDesignPublicationOperation.fromStored(original).canonicalBytes()) + .containsExactly(original); + var afterRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThat(afterRead.operation().canonicalBytes()).containsExactly(original); + assertThat(afterRead.outcome()).isEqualTo(beforeRead.outcome()).isEqualTo("PENDING"); + assertThat(afterRead.receiptBytes()).isEqualTo(beforeRead.receiptBytes()); + assertThatThrownBy(afterRead.operation()::inventory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + assertEnabledGuards(fixture); + + deny( + fixture, + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .operations() + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false)), + "Truncated publication inventory frame"); + for (String family : List.of("command", "realm_policy", "asset")) { + deny( + fixture, () -> insertV1Capture(fixture, family), "Truncated publication inventory frame"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM " + + captureTable(family) + + " WHERE publish_workflow_id = ?", + operation.workflowId()) + .get(0, Long.class)) + .isZero(); + } + deny( + fixture, + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_publication_operation WHERE publish_workflow_id = ?", + operation.workflowId()), + "publication operation history is immutable"); + assertThat(retainedRows(fixture)).isEqualTo(rows); + assertThat(predecessorChecksums(fixture)).isEqualTo(migrationHistory); + assertThat( + fixture + .operations() + .read(operation.workflowId()) + .orElseThrow() + .operation() + .canonicalBytes()) + .containsExactly(original); + } + + @Test + void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() + throws Exception { + var fixture = fixture(false, true); + var binding = fixture.operation().account().input().selection().selectedCommit(); + var beforeRow = reviewedBaseRow(fixture, binding); + var before = + fixture + .dsl() + .fetchOne( + "SELECT evidence_schema, evidence_bytes, evidence_digest FROM game_design_reviewed_draft_base WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()); + assertThat(before).isNotNull(); + var originalBytes = before.get("evidence_bytes", byte[].class); + var originalDigest = before.get("evidence_digest", String.class); + assertThat(before.get("evidence_schema", String.class)) + .isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + assertThat(originalDigest).isEqualTo(DraftAuthorizationFenceBinding.digest(originalBytes)); + var beforeRead = + new GameDesignReviewedBaseRepository(fixture.dsl()).read(binding).orElseThrow(); + assertThat(beforeRead.schema()).isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + assertThat(beforeRead.canonicalBytes()).containsExactly(originalBytes); + assertThat(beforeRead.digest()).isEqualTo(originalDigest); + var parentChecksums = predecessorChecksums(fixture); + + upgrade(fixture); + + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1024); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(84L); + assertThat(predecessorChecksums(fixture)).isEqualTo(parentChecksums); + assertThat(reviewedBaseRow(fixture, binding)).isEqualTo(beforeRow); + var retained = new GameDesignReviewedBaseRepository(fixture.dsl()).read(binding).orElseThrow(); + assertThat(retained.schema()).isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + assertThat(retained.canonicalBytes()).containsExactly(originalBytes); + assertThat(retained.digest()).isEqualTo(originalDigest); + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository(fixture.dsl()).requireCurrentRetained(binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("REVIEWED_BASE_ASSET_LINEAGE_UNAVAILABLE"); + assertEnabledGuards(fixture); + + denyReviewedBase( + fixture, + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_reviewed_draft_base SET evidence_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + "sha256:" + "0".repeat(64), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()), + "Reviewed Draft base evidence is immutable"); + denyReviewedBase( + fixture, + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_reviewed_draft_base WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()), + "Reviewed Draft base evidence is immutable"); + + var newBinding = + DraftCommitBinding.create( + binding.target(), + UUID.randomUUID(), + UUID.randomUUID(), + binding.baseCommitId(), + binding.revisions(), + binding.affectedUnits()); + fixture + .write() + .executeWithoutResult( + status -> new DraftCommitCoordinatorRepository(fixture.dsl()).claim(newBinding)); + denyReviewedBase( + fixture, + () -> + fixture + .write() + .executeWithoutResult( + status -> + insertReviewedBaseV1( + fixture.dsl(), + newBinding, + originalBytes, + originalDigest, + newBinding.baseCommitId())), + "Fresh reviewed base requires complete asset-bound v2 owner evidence"); + assertThat(reviewedBaseRow(fixture, binding)).isEqualTo(beforeRow); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM game_design_reviewed_draft_base WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + newBinding.target().canonicalTenantId(), + newBinding.target().canonicalVersionId(), + newBinding.requestId())) + .isNull(); + } + + @Test + void retainedTerminalFailureRemainsReadableWithItsOriginalReceiptAfterUpgrade() throws Exception { + var fixture = fixture(true); + var operation = fixture.operation(); + fixture + .write() + .executeWithoutResult( + status -> { + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_STORAGE_DENIAL"); + attempts.save(attempt); + fixture + .operations() + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + }); + var original = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); + assertThat(original.receiptBytes()).isNotEmpty(); + assertThat(original.terminalEvidenceBytes()).isNotEmpty(); + var rows = retainedRows(fixture); + var checksums = predecessorChecksums(fixture); + upgrade(fixture); + var retained = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThat(retained.operation().canonicalBytes()).containsExactly(operation.canonicalBytes()); + assertThat(retained.outcome()).isEqualTo(original.outcome()); + assertThat(retained.receiptBytes()).containsExactly(original.receiptBytes()); + assertThat(retained.terminalEvidenceBytes()).containsExactly(original.terminalEvidenceBytes()); + assertThat(retainedRows(fixture)).isEqualTo(rows); + assertThat(predecessorChecksums(fixture)).isEqualTo(checksums); + assertEnabledGuards(fixture); + } + + @Test + void newParentV1ReservationIsDeniedAndRawV2ReservationUsesActualOwnerSelectionAndAttempt() + throws Exception { + // Actual owner selection/attempt, deliberately not auto-reserved by the v1 fixture helper. + var fixture = fixture(false); + var before = retainedRows(fixture); + upgrade(fixture); + assertEnabledGuards(fixture); + deny( + fixture, + () -> + fixture + .write() + .executeWithoutResult(status -> fixture.operations().reserve(fixture.operation())), + "Truncated publication inventory frame"); + assertThat(retainedRows(fixture)).isEqualTo(before); + + byte[] inventory = canonical(inventory(fixture.operation())); + byte[] originalV2 = operationBytes(fixture.operation(), inventory); + requireInventory(fixture, originalV2); + deny( + fixture, + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_publication_operation (publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + fixture.operation().workflowId(), + fixture.operation().tenantKey(), + fixture.operation().versionId(), + "sha256:" + "f".repeat(64), + originalV2)), + "publication operation does not bind exact selected attempt"); + assertThat(retainedRows(fixture)).isEqualTo(before); + fixture.write().executeWithoutResult(status -> insertOperation(fixture, originalV2)); + var stored = + fixture + .dsl() + .fetchOne( + "SELECT request_bytes, outcome, revision, selection_digest FROM game_design_publication_operation WHERE publish_workflow_id = ?", + fixture.operation().workflowId()); + assertThat(stored).isNotNull(); + assertThat(stored.get("request_bytes", byte[].class)).containsExactly(originalV2); + assertThat(stored.get("outcome", String.class)).isEqualTo("PENDING"); + assertThat(stored.get("revision", Long.class)).isEqualTo(1L); + assertThat(stored.get("selection_digest", String.class)) + .isEqualTo(fixture.operation().selectionDigest()); + // The evolved decoder preserves complete v2 while retained v1 remains a separate read profile. + var decoded = GameDesignPublicationOperation.fromStored(originalV2); + assertThat(decoded.canonicalBytes()).containsExactly(originalV2); + assertThat(decoded.account().canonicalBytes()) + .containsExactly(fixture.operation().account().canonicalBytes()); + assertThat(decoded.world().canonicalBytes()) + .containsExactly(fixture.operation().world().canonicalBytes()); + assertThat(decoded.inventory().canonicalBytes()).containsExactly(inventory); + assertThat(decoded.inventory().digest()).isEqualTo(sha256(inventory)); + byte[] beforeRow = canonicalRow(fixture, "game_design_publication_operation"); + deny( + fixture, + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET request_bytes = ? WHERE publish_workflow_id = ?", + originalV2, + fixture.operation().workflowId()), + "publication operation identity or terminal outcome is immutable"); + assertThat(canonicalRow(fixture, "game_design_publication_operation")) + .containsExactly(beforeRow); + } + + @Test + void actualInventoryGuardRejectsMalformedFramesDigestUnknownFieldsAndExactBindingChanges() + throws Exception { + var fixture = fixture(false); + upgrade(fixture); + byte[] inventory = canonical(inventory(fixture.operation())); + byte[] valid = operationBytes(fixture.operation(), inventory); + requireInventory(fixture, valid); + var before = retainedRows(fixture); + List malformed = new ArrayList<>(); + malformed.add(fixture.operation().canonicalBytes()); + malformed.add(Arrays.copyOf(valid, valid.length - 1)); + malformed.add(Arrays.copyOf(valid, valid.length + 1)); + malformed.add( + framed( + "game-design-publication-operation/v999", + fixture.operation(), + inventory, + sha256(inventory))); + malformed.add(framed(V2, fixture.operation(), inventory, "sha256:" + "0".repeat(64))); + malformed.add(new byte[4 * 1024 * 1024 + 1]); + var unknown = inventory(fixture.operation()); + unknown.put("undeclaredFamily", List.of()); + malformed.add(operationBytes(fixture.operation(), canonical(unknown))); + var wrongAccount = inventory(fixture.operation()); + member(wrongAccount, "accountOrder").put("fenceId", UUID.randomUUID().toString()); + malformed.add(operationBytes(fixture.operation(), canonical(wrongAccount))); + var wrongGraph = inventory(fixture.operation()); + member(wrongGraph, "sourceModel").put("graphDigest", "sha256:" + "1".repeat(64)); + malformed.add(operationBytes(fixture.operation(), canonical(wrongGraph))); + var missingFamily = inventory(fixture.operation()); + member(missingFamily, "sourceModel").put("familyCounts", List.of()); + malformed.add(operationBytes(fixture.operation(), canonical(missingFamily))); + byte[] duplicateMember = + (new String(inventory, StandardCharsets.UTF_8).replaceFirst("\\{", "{\"schemaVersion\":1,")) + .getBytes(StandardCharsets.UTF_8); + malformed.add(operationBytes(fixture.operation(), duplicateMember)); + for (byte[] bytes : malformed) { + deny(fixture, () -> requireInventory(fixture, bytes), null); + } + assertThat(retainedRows(fixture)).isEqualTo(before); + assertEnabledGuards(fixture); + } + + @Test + void closureProfileRequiresExactSchemaPairAndExplicitEmptyInboundEnumeration() throws Exception { + var fixture = fixture(false); + upgrade(fixture); + var closure = inventory(fixture.operation()); + closure.put("schema", "world-selected-publication-artifact-inventory/v2"); + closure.put("schemaVersion", 2); + member(closure, "checkpoint").put("digestSchemaVersion", 4); + var model = member(closure, "sourceModel"); + model.put("modelId", "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1"); + model.put("graphSchemaVersion", 3); + model.put("inboundSourceClosure", Map.of("schemaVersion", 1, "familyCounts", inboundCounts(0))); + var world = JSON.readValue(fixture.operation().world().canonicalBytes(), Map.class); + member(world, "request").put("digestSchemaVersion", 4); + byte[] worldBytes = canonical(world); + byte[] closureBytes = + framed( + V2, + fixture.operation().account().canonicalBytes(), + worldBytes, + canonical(closure), + sha256(canonical(closure))); + requireInventory(fixture, closureBytes); + + var wrongProfile = copy(closure); + member(wrongProfile, "sourceModel").put("graphSchemaVersion", 2); + deny( + fixture, + () -> + requireInventory( + fixture, + framed( + V2, + fixture.operation().account().canonicalBytes(), + worldBytes, + canonical(wrongProfile), + sha256(canonical(wrongProfile)))), + null); + var nonempty = copy(closure); + member(nonempty, "sourceModel") + .put("inboundSourceClosure", Map.of("schemaVersion", 1, "familyCounts", inboundCounts(1))); + deny( + fixture, + () -> + requireInventory( + fixture, + framed( + V2, + fixture.operation().account().canonicalBytes(), + worldBytes, + canonical(nonempty), + sha256(canonical(nonempty)))), + null); + var missing = copy(closure); + member(missing, "sourceModel").remove("inboundSourceClosure"); + deny( + fixture, + () -> + requireInventory( + fixture, + framed( + V2, + fixture.operation().account().canonicalBytes(), + worldBytes, + canonical(missing), + sha256(canonical(missing)))), + null); + deny( + fixture, + () -> requireInventory(fixture, operationBytes(fixture.operation(), canonical(closure))), + null); + assertEnabledGuards(fixture); + } + + private Fixture fixture(boolean reserveV1) throws Exception { + return fixture(reserveV1, false); + } + + private Fixture fixture(boolean reserveV1, boolean retainReviewedV1) throws Exception { + String schema = "gd_storage_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + flyway(dataSource, schema, "50.16").migrate(); + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + 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(dataSource))); + configuration.set( + new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider( + new DataSourceTransactionManager(dataSource))); + var dsl = DSL.using(configuration); + var operation = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED passive storage owner"); + var game = new GameRepository(dsl).save(requested); + // Reproduce the original owner insertion under its actual pre-tail schema. The + // current Version writer requires ordinary asset genesis, which did not exist here. + var inserted = + java.util.Objects.requireNonNull( + 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, is_script_only, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, 1, 'DRAFT', 1, FALSE, " + + "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + game.getId())); + var version = + new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + RealmPolicyGenesis reviewedGenesis = null; + String reviewedBaseReference = null; + if (retainReviewedV1) { + reviewedGenesis = new RealmPolicySourceRepository(dsl).recordFreshGenesis(target); + new CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + target, + reviewedGenesis.receiptId(), + reviewedGenesis.creationTransactionId())); + reviewedBaseReference = "genesis:" + reviewedGenesis.receiptId(); + } + try { + return reserveV1 + ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( + dsl, target, version.getVersionStateEpoch()) + : prepareUnreservedOwnerOperation( + dsl, target, version, reviewedBaseReference, reviewedGenesis); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + return new Fixture( + dataSource, + schema, + dsl, + write, + operation, + new GameDesignPublicationOperationRepository(dsl)); + } + + private GameDesignPublicationOperation prepareUnreservedOwnerOperation( + DSLContext dsl, + TargetProof target, + Version version, + String baseReference, + RealmPolicyGenesis reviewedGenesis) + throws Exception { + var seed = + baseReference == null + ? IsolatedPublicationOperationFixtures.fresh(target) + : IsolatedPublicationOperationFixtures.fresh(target, baseReference); + var draft = seed.account().input().selection().selectedCommit(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claim(draft); + if (reviewedGenesis != null) { + var commandGenesis = + new CommandSourceRepository(dsl).readNewDraftGenesis(target).orElseThrow(); + var evidenceBytes = + historicalReviewedGenesisBytes(draft.target(), reviewedGenesis, commandGenesis); + insertReviewedBaseV1( + dsl, + draft, + evidenceBytes, + DraftAuthorizationFenceBinding.digest(evidenceBytes), + draft.baseCommitId()); + } + coordinator.claimApplicationSlot(draft); + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + 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.recordOwnerOutcome(draft, outcome); + IsolatedPublicationOwnerSetup.advanceIsolatedVisibility(dsl, draft, List.of(outcome)); + coordinator.releaseApplicationSlot(draft); + var selection = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + UUID.randomUUID().toString(), + Long.toString(version.getVersionStateEpoch()), + "ISOLATED passive storage input", + draft.requestId(), + draft.commitId(), + draft.digest())) + .selection(); + var operation = + IsolatedPublicationOperationFixtures.historicalV1ForSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + seed.world()); + var attempt = new PublishAttempt(); + attempt.setTenantId(operation.tenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(operation.versionId()); + attempt.setVersionNumber(version.getVersionNumber()); + attempt.setRequestDigest(operation.selectionDigest()); + new PublishAttemptRepository(dsl).save(attempt); + return operation; + } + + private byte[] historicalReviewedGenesisBytes( + TargetProof target, + RealmPolicyGenesis policyGenesis, + CommandSource.NewDraftGenesisReceipt commandGenesis) { + var ownerEvidence = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(ownerEvidence, "shared-policy-command-genesis/v1"); + DraftAuthorizationFenceBinding.frame(ownerEvidence, policyGenesis.creationTransactionId()); + DraftAuthorizationFenceBinding.frame(ownerEvidence, policyGenesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(ownerEvidence, commandGenesis.canonicalBytes()); + + var evidence = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + evidence, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + DraftAuthorizationFenceBinding.frame(evidence, DraftBaseReference.SCHEMA); + DraftAuthorizationFenceBinding.frame(evidence, DraftBaseReference.Kind.GENESIS.name()); + DraftAuthorizationFenceBinding.frame(evidence, "genesis:" + policyGenesis.receiptId()); + DraftAuthorizationFenceBinding.frame(evidence, target.canonicalTenantId().toString()); + DraftAuthorizationFenceBinding.frame(evidence, target.canonicalVersionId().toString()); + DraftAuthorizationFenceBinding.frame(evidence, Long.toString(target.gameDesignVersionRowId())); + DraftAuthorizationFenceBinding.frame(evidence, target.gameDesignVersionTenantKey()); + DraftAuthorizationFenceBinding.frame(evidence, Long.toString(target.sourceGameRowId())); + DraftAuthorizationFenceBinding.frame(evidence, target.sourceGameTenantKey()); + DraftAuthorizationFenceBinding.frame(evidence, target.sourceProvenanceKind()); + DraftAuthorizationFenceBinding.frame(evidence, ownerEvidence.toByteArray()); + return evidence.toByteArray(); + } + + private void insertReviewedBaseV1( + DSLContext dsl, + DraftCommitBinding binding, + byte[] evidenceBytes, + String evidenceDigest, + String baseReference) { + var reference = DraftBaseReference.parse(baseReference); + 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.HISTORICAL_SCHEMA, + evidenceBytes, + evidenceDigest); + } + + private String reviewedBaseRow(Fixture fixture, DraftCommitBinding binding) { + return fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(b)::TEXT FROM game_design_reviewed_draft_base b WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()) + .get(0, String.class); + } + + private Flyway flyway(DriverManagerDataSource source, String schema, String target) { + return flyway(source, schema, target, "classpath:db/migration", "classpath:db/migration/saga"); + } + + private Flyway flyway( + DriverManagerDataSource source, String schema, String target, String... locations) { + var builder = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(locations) + .table("flyway_schema_history_game_design_service"); + if (target != null) builder.target(target); + return builder.load(); + } + + private void upgrade(Fixture fixture) { + flyway(fixture.source(), fixture.schema(), null).migrate(); + flyway(fixture.source(), fixture.schema(), null).validate(); + } + + private List predecessorChecksums(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND installed_rank <= 59 ORDER BY installed_rank") + .getValues(0, String.class); + } + + private Map retainedRows(Fixture fixture) { + var rows = new LinkedHashMap(); + for (String table : + List.of( + "game", + "version", + "game_design_draft_commit", + "game_design_draft_commit_owner_result", + "game_design_draft_commit_visibility_fence", + "game_design_authored_draft_publish_selection", + "publish_attempt", + "game_design_publication_operation")) { + byte[] bytes = canonicalRow(fixture, table); + rows.put(table, new String(bytes, StandardCharsets.UTF_8) + ":" + sha256(bytes)); + } + return rows; + } + + private byte[] canonicalRow(Fixture fixture, String table) { + return fixture + .dsl() + .fetchSingle( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)::TEXT), '[]'::JSONB)::TEXT FROM " + + table + + " r") + .get(0, String.class) + .getBytes(StandardCharsets.UTF_8); + } + + private void assertEnabledGuards(Fixture fixture) { + assertEnabledGuards(fixture.dsl(), fixture.schema()); + } + + private void assertEnabledGuards(DSLContext dsl, String schema) { + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", + schema) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND t.tgname IN ('game_design_publication_operation_guard','publication_terminal_extension_guard','publication_operation_commit_guard','realm_policy_capture_guard','command_source_capture_guard','ordinary_asset_capture_guard') AND t.tgenabled = 'O'", + schema) + .get(0, Long.class)) + .isEqualTo(6L); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND t.tgname IN ('command_capture_inventory_v2','policy_capture_inventory_v2','asset_capture_inventory_v2','a_published_policy_inventory_v2')", + schema) + .get(0, Long.class)) + .isEqualTo(4L); + } + + private void insertV1Capture(Fixture fixture, String family) { + var operation = fixture.operation(); + // Every pre-existing source/lifecycle guard remains enabled. The new BEFORE INSERT guard + // rejects legacy operation framing before these deliberately inadmissible new captures exist. + String digestColumns = family.equals("realm_policy") ? "" : ", capture_digest"; + String digestValues = family.equals("realm_policy") ? "" : ", ?"; + var args = + new ArrayList( + List.of( + operation.account().tenantId(), + operation.world().request().canonicalVersionId(), + operation.workflowId(), + operation.account().input().selection().selectedCommit().commitId(), + operation.canonicalBytes(), + new byte[] {1})); + if (!family.equals("realm_policy")) args.add("sha256:" + "0".repeat(64)); + String table = captureTable(family); + fixture + .dsl() + .execute( + "INSERT INTO " + + table + + " (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes" + + digestColumns + + ") VALUES (?, ?, ?, ?, ?, ?" + + digestValues + + ")", + args.toArray()); + } + + private String captureTable(String family) { + return family.equals("realm_policy") + ? "game_design_realm_policy_capture" + : "game_design_" + family + "_source_capture"; + } + + private void insertOperation(Fixture fixture, byte[] bytes) { + var operation = fixture.operation(); + fixture + .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(), + bytes); + } + + private void requireInventory(Fixture fixture, byte[] bytes) { + fixture.dsl().fetch("SELECT require_selected_inventory_operation_v2(?::BYTEA)", bytes); + } + + private void deny(Fixture fixture, Runnable write, String message) { + assertThatThrownBy(write::run) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + if (message != null) assertThat(cause.getMessage()).contains(message); + }); + } + + private void denyReviewedBase(Fixture fixture, Runnable write, String message) { + assertThatThrownBy(write::run) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("P0001"); + if (message != null) assertThat(cause.getMessage()).contains(message); + }); + } + + /** Raw supplied external inventory, matching the published isolated fixture's closed profile. */ + private Map inventory(GameDesignPublicationOperation operation) throws Exception { + var account = operation.account(); + var selection = account.input().selection(); + var commit = selection.selectedCommit(); + var world = operation.world(); + var request = world.request(); + var original = DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + String fixtureId = + UUID.nameUUIDFromBytes("ISOLATED World inventory input".getBytes(StandardCharsets.UTF_8)) + .toString(); + var result = new LinkedHashMap(); + result.put("schema", "world-selected-publication-artifact-inventory/v1"); + result.put("schemaVersion", 1); + result.put("completeness", "COMPLETE"); + result.put( + "ownerScope", + Map.of( + "targetNamespace", + request.targetNamespace(), + "canonicalTenantId", + request.canonicalTenantId().toString(), + "canonicalVersionId", + request.canonicalVersionId().toString(), + "versionIdentityOperationId", + fixtureId, + "intakeRequestId", + request.intakeRequestId().toString(), + "intakeOperationId", + fixtureId, + "intakeRequestDigest", + sha256(world.originalAccountBindingBytes()), + "sourceOperationId", + fixtureId, + "sourceEvidenceDigest", + sha256(world.selectorReceiptBytes()), + "intakeReceiptDigest", + sha256(world.selectorReceiptBytes()))); + result.put( + "selectedApplication", + Map.of( + "applicationOperationId", + original.operationId().toString(), + "applicationRequestId", + commit.requestId().toString(), + "appliedCommitId", + commit.commitId().toString(), + "bindingDigest", + commit.digest(), + "appliedResultDigest", + sha256(world.appliedResultBytes()))); + result.put( + "accountOrder", + Map.of( + "operationId", + account.operationId().toString(), + "fenceId", + account.fenceId().toString(), + "actorAccountId", + account.input().actorAccountId().toString(), + "publicationRequestId", + selection.intent().publishRequestId(), + "selectionDigest", + selection.digest(), + "selectedCommitId", + commit.commitId().toString(), + "bindingDigest", + sha256(account.canonicalBytes()))); + result.put( + "freeze", + Map.of( + "publicationFence", + request.publicationFence().toString(), + "publicationRequestId", + request.publicationRequestId(), + "requestDigest", + request.requestDigest(), + "versionStateEpoch", + Long.toString(request.versionStateEpoch()), + "publishWorkflowId", + request.publishWorkflowId())); + result.put( + "checkpoint", + new LinkedHashMap<>( + Map.of( + "appliedCommitId", + request.appliedCommitId(), + "contentDigest", + request.contentDigest(), + "digestSchemaVersion", + request.digestSchemaVersion()))); + var model = new LinkedHashMap(); + model.put("modelId", "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"); + model.put("graphSchemaVersion", 2); + model.put( + "graphDigest", + WorldDraftStartLocationEvidence.fromStored(world.selectorReceiptBytes()).graphDigest()); + model.put( + "topologyResultDigest", + sha256("ISOLATED topology result".getBytes(StandardCharsets.UTF_8))); + model.put( + "familyCounts", + List.of( + Map.of("family", "REGION", "rowCount", 1), + Map.of("family", "ZONE", "rowCount", 1), + Map.of("family", "ROOM", "rowCount", 1), + Map.of("family", "ROOM_EXIT", "rowCount", 0), + Map.of("family", "GENERATION_RULE", "rowCount", 0), + Map.of("family", "WORLD_ENTITY_SPAWN_BINDING", "rowCount", 0))); + model.put( + "regionGeneratorInputs", + List.of(Map.of("regionTemplateId", fixtureId, "generatorType", "", "generatorParams", ""))); + model.put("generationRuleFields", List.of("id", "name", "scopeType", "scopeId", "value")); + model.put( + "regionFields", + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier")); + model.put("zoneFields", List.of("id", "regionId", "name")); + model.put( + "roomFields", + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson")); + model.put("roomExitFields", List.of("id", "fromRoomId", "toRoomId", "direction", "cost")); + model.put( + "spawnBindingFields", + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds")); + model.put("spawnBindingInputs", List.of()); + model.put("generationRuleInputCount", 0); + model.put("spawnBindingCount", 0); + model.put( + "appliedEpochs", + commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).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()); + result.put("sourceModel", model); + result.put( + "artifactDecisions", + List.of( + Map.of( + "artifactKind", + "NAVMESH", + "state", + "NOT_REQUIRED", + "rule", + "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + Map.of( + "artifactKind", + "PATH_GRAPH", + "state", + "NOT_REQUIRED", + "rule", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + return result; + } + + private List> inboundCounts(int firstCount) { + var families = + List.of( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"); + var counts = new ArrayList>(); + for (int i = 0; i < families.size(); i++) + counts.add(Map.of("family", families.get(i), "count", i == 0 ? firstCount : 0)); + return counts; + } + + @SuppressWarnings("unchecked") + private Map member(Map object, String key) { + // Mutations create independent supplied negatives, never validate or synthesize owner truth. + var value = (Map) object.get(key); + if (!(value instanceof LinkedHashMap)) { + value = new LinkedHashMap<>(value); + ((Map) object).put(key, value); + } + return value; + } + + @SuppressWarnings("unchecked") + private Map copy(Map value) throws Exception { + return JSON.readValue(canonical(value), Map.class); + } + + private byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw new IllegalStateException("Cannot encode supplied inventory test data", failure); + } + } + + private byte[] operationBytes(GameDesignPublicationOperation operation, byte[] inventory) { + return framed(V2, operation, inventory, sha256(inventory)); + } + + private byte[] framed( + String schema, GameDesignPublicationOperation operation, byte[] inventory, String digest) { + return framed( + schema, + operation.account().canonicalBytes(), + operation.world().canonicalBytes(), + inventory, + digest); + } + + private byte[] framed( + String schema, byte[] account, byte[] world, byte[] inventory, String digest) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, account); + DraftAuthorizationFenceBinding.frame(out, world); + DraftAuthorizationFenceBinding.frame(out, inventory); + DraftAuthorizationFenceBinding.frame(out, digest); + return out.toByteArray(); + } + + private String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + DriverManagerDataSource source, + String schema, + DSLContext dsl, + TransactionTemplate write, + GameDesignPublicationOperation operation, + GameDesignPublicationOperationRepository operations) {} +} 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 index cd10f8ad79..e5f6313bcb 100644 --- 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 @@ -32,10 +32,15 @@ import java.security.Security; import java.security.cert.X509Certificate; import java.time.Instant; +import java.util.ArrayList; import java.util.Base64; +import java.util.Comparator; import java.util.Date; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -570,7 +575,7 @@ void authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation() th @Test void retainedV50_6TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() throws Exception { - var fixture = fixture("50.6"); + var fixture = historicalFixture("50.6"); assertThat(fixture.candidate()).isNull(); var op = fixture.operation(); var old = new ByteArrayOutputStream(); @@ -620,8 +625,93 @@ void retainedV50_6TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch } @Test - void publicationReceiptSurvivesAdditiveReleaseColumnAndFreshSealAfterAddition() throws Exception { - var retained = fixture(); + void retainedPreV56V1OperationStaysByteExactReadableAndReadOnlyAfterV56AndV70() throws Exception { + var fixture = historicalOperationOnlyFixture("50.7"); + var operation = fixture.operation(); + byte[] originalRequest = operation.canonicalBytes(); + new DraftAuthorizationFenceBinding.FrameReader(originalRequest) + .expect("game-design-publication-operation/v1"); + var before = operationSnapshot(fixture); + assertThat(before.requestBytes()).isEqualTo(originalRequest); + assertThat(before.requestChecksum()).isEqualTo(sha256(originalRequest)); + assertThatThrownBy(operation::inventory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + + fixture.completeMigration().run(); + + var afterMigration = operationSnapshot(fixture); + assertThat(afterMigration.rowJson()).isEqualTo(before.rowJson()); + assertThat(afterMigration.requestBytes()).isEqualTo(before.requestBytes()); + assertThat(afterMigration.requestChecksum()).isEqualTo(before.requestChecksum()); + assertThat(afterMigration.rowChecksum()).isEqualTo(before.rowChecksum()); + var retained = fixture.service().readExact(operation).orElseThrow(); + assertThat(retained.operation().canonicalBytes()).isEqualTo(originalRequest); + assertThat(retained.outcome()).isEqualTo("PENDING"); + + assertThatThrownBy( + () -> + fixture + .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(), + originalRequest)) + .hasMessageContaining("Truncated publication inventory frame"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " + + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + new byte[] {1}, + operation.workflowId())) + .hasMessageContaining("Truncated publication inventory frame"); + + var selection = operation.account().input().selection(); + assertThatThrownBy( + () -> + fixture + .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 (?, ?, ?, ?, ?, ?)", + operation.account().tenantId(), + operation.world().request().canonicalVersionId(), + operation.workflowId(), + selection.selectedCommit().commitId(), + originalRequest, + new byte[] {1})) + .hasMessageContaining("Truncated publication inventory frame"); + + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_design_realm_policy_capture WHERE publish_workflow_id = ?", + operation.workflowId()) + .get(0, Long.class)) + .isZero(); + var afterDeniedWrites = operationSnapshot(fixture); + assertThat(afterDeniedWrites.rowJson()).isEqualTo(before.rowJson()); + assertThat(afterDeniedWrites.requestBytes()).isEqualTo(before.requestBytes()); + assertThat(afterDeniedWrites.requestChecksum()).isEqualTo(before.requestChecksum()); + assertThat(afterDeniedWrites.rowChecksum()).isEqualTo(before.rowChecksum()); + assertThat(fixture.service().readExact(operation).orElseThrow().outcome()).isEqualTo("PENDING"); + } + + @Test + void retainedPublicationReceiptSurvivesAdditiveReleaseColumnAndV1SealIsDeniedAfterV56() + throws Exception { + var retained = historicalFixture("50.7"); publish(retained); var original = retained.service().readExact(retained.operation()).orElseThrow(); String originalEvidence = @@ -684,6 +774,24 @@ void publicationReceiptSurvivesAdditiveReleaseColumnAndFreshSealAfterAddition() assertThat(retained.service().readExact(retained.operation()).orElseThrow().receiptBytes()) .isEqualTo(original.receiptBytes()); + var retainedPending = historicalFixture("50.7"); + var originalOperationBytes = retainedPending.operation().canonicalBytes(); + retainedPending.completeMigration().run(); + assertThatThrownBy( + () -> + retainedPending + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " + + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + new byte[] {1}, + retainedPending.operation().workflowId())) + .hasMessageContaining("Truncated publication inventory frame"); + var stillPending = + retainedPending.service().readExact(retainedPending.operation()).orElseThrow(); + assertThat(stillPending.outcome()).isEqualTo("PENDING"); + assertThat(stillPending.operation().canonicalBytes()).isEqualTo(originalOperationBytes); + var fresh = fixture(); fresh.completeMigration().run(); fresh @@ -709,6 +817,24 @@ private ReadCollector readThroughHandler( return readThroughHandler(fixture, request, service, fixture.service()); } + private OperationRowSnapshot operationSnapshot(Fixture fixture) { + var row = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(o)::TEXT AS row_json, o.request_bytes, " + + "'sha256:' || encode(sha256(o.request_bytes), 'hex') AS request_checksum " + + "FROM game_design_publication_operation o WHERE publish_workflow_id = ?", + fixture.operation().workflowId())); + String rowJson = row.get("row_json", String.class); + return new OperationRowSnapshot( + rowJson, + row.get("request_bytes", byte[].class), + row.get("request_checksum", String.class), + sha256(rowJson.getBytes(StandardCharsets.UTF_8))); + } + private ReadCollector readThroughHandler( Fixture fixture, GameDesignPublicationTerminalReadEvidence.ReadRequest request, @@ -1124,14 +1250,31 @@ private void publishInTransaction(Fixture fixture, boolean seal) { 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); + if (fixture.historicalV1()) { + int updatedArtifact = + fixture + .dsl() + .execute( + "UPDATE version_asset_artifact SET artifact_state = 'PUBLISHED', " + + "state_epoch = state_epoch + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE tenant_id = ? AND version_id = ? AND artifact_state = 'STAGED' " + + "AND state_epoch = 2 AND last_workflow_id = ?", + op.tenantKey(), + op.versionId(), + op.workflowId()); + if (updatedArtifact != 1) { + throw new IllegalStateException("HISTORICAL_ASSET_ARTIFACT_TRANSITION_CONFLICT"); + } + } else { + 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); @@ -1239,10 +1382,6 @@ private void rawReleaseInsert(Fixture fixture) { bundle.getWorldPublishedStartLocationEvidenceJson()); } - private Fixture fixture() throws Exception { - return fixture("50.7"); - } - private Version insertRetainedVersion( DSLContext dsl, VersionRepository versions, Game game, int versionNumber) { var inserted = @@ -1264,22 +1403,42 @@ private Version insertRetainedVersion( return versions.findById(inserted.get("id", Long.class)).orElseThrow(); } - private Fixture fixture(String migrationTarget) throws Exception { + private Fixture fixture() throws Exception { + return fixture(null, false, true); + } + + private Fixture historicalFixture(String migrationTarget) throws Exception { + return fixture(migrationTarget, true, true); + } + + /** This profile proves retained operation history without seeding unrelated old asset rows. */ + private Fixture historicalOperationOnlyFixture(String migrationTarget) throws Exception { + return fixture(migrationTarget, true, false); + } + + private Fixture fixture( + String migrationTarget, boolean historicalV1, boolean includeAssetCandidate) + throws Exception { + if (historicalV1 && !List.of("50.6", "50.7").contains(migrationTarget)) { + throw new IllegalArgumentException("Historical operation fixture must target pre-V56 schema"); + } 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 flyway = + 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"); + if (migrationTarget != null) { + flyway.target(migrationTarget); + } + flyway.load().migrate(); var transactions = new DataSourceTransactionManager(source); var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -1303,10 +1462,16 @@ private Fixture fixture(String migrationTarget) throws Exception { 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)); + Version version; + if (historicalV1) { + // Retained pre-V56 rows use the original Version shape and operation framing. + version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); + } else { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + version = write.execute(status -> versions.save(requested)); + } var target = new TargetProof( version.getCanonicalTenantId(), @@ -1316,21 +1481,10 @@ private Fixture fixture(String migrationTarget) throws Exception { 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)) { + GameAsset asset = null; + if (includeAssetCandidate && !"50.6".equals(migrationTarget)) { var gameAssets = new GameAssetRepository(dsl); - var asset = + asset = write.execute( status -> { var requested = new GameAsset(); @@ -1340,54 +1494,73 @@ private Fixture fixture(String migrationTarget) throws Exception { 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); } + GameAsset fixtureAsset = asset; + var operation = + write.execute( + status -> { + try { + return historicalV1 + ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( + dsl, target, version.getVersionStateEpoch()) + : IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, + target, + version.getVersionStateEpoch(), + "ISOLATED selected source and publication fixture", + List.of( + new IsolatedPublicationOwnerSetup.OrdinaryAsset( + Objects.requireNonNull(fixtureAsset).getId(), ASSET_FILE_NAME))); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var operations = new GameDesignPublicationOperationRepository(dsl); var artifacts = new VersionAssetArtifactRepository(dsl); + FrozenAssetExportCandidate readCandidate = null; + if (includeAssetCandidate && !"50.6".equals(migrationTarget)) { + if (historicalV1) { + var snapshot = + seedHistoricalAssetSnapshot( + dsl, write, game, version, Objects.requireNonNull(fixtureAsset)); + readCandidate = + seedHistoricalAssetCandidate(dsl, write, game, version, operation, snapshot); + } else { + var publicationRepository = new VersionAssetPublicationRepository(dsl); + var snapshot = + write.execute( + status -> + publicationRepository.freezeOrReadSnapshot( + game.getTenantId(), version.getVersionNumber())); + var artifactService = + new VersionAssetArtifactServiceImpl( + artifacts, null, versions, null, null, null, null, null, new ObjectMapper()); + write.execute( + status -> + artifactService.stageExport( + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + 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); + } + } return new Fixture( dsl, write, @@ -1399,6 +1572,7 @@ private Fixture fixture(String migrationTarget) throws Exception { new GameDesignPublicationOperationService(operations, transactions), operation, readCandidate, + historicalV1, () -> Flyway.configure() .dataSource(source) @@ -1445,6 +1619,178 @@ private FrozenAssetExportCandidate candidate( PUBLIC_BASE_URL); } + /** + * Seeds the actual V37 mapping/export rows that existed before V55 introduced source projection. + * The old schema permits these owner rows directly; no modern ASSET_REFERENCE evidence is + * fabricated for a Version created before that contract existed. + */ + private VersionAssetPublicationRepository.ExportSnapshot seedHistoricalAssetSnapshot( + DSLContext dsl, TransactionTemplate write, Game game, Version version, GameAsset asset) { + String contentDigest = sha256(ASSET_BYTES); + write.executeWithoutResult( + status -> { + dsl.execute( + "INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key, usage_type) " + + "VALUES (?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + asset.getId(), + ASSET_FILE_NAME, + "logo"); + dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + ASSET_FILE_NAME, + asset.getId(), + ASSET_CONTENT_TYPE, + contentDigest, + (long) ASSET_BYTES.length); + dsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, " + + "version_number, captured_version_state_epoch, item_count) " + + "VALUES (?, ?, ?, ?, ?, ?, 1)", + game.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getVersionNumber(), + version.getVersionStateEpoch()); + }); + return new VersionAssetPublicationRepository(dsl) + .readFrozenSnapshot(game.getTenantId(), version.getVersionNumber()); + } + + /** Persists and rereads the original V38/V50 candidate shape without V65 inventory authority. */ + private FrozenAssetExportCandidate seedHistoricalAssetCandidate( + DSLContext dsl, + TransactionTemplate write, + Game game, + Version version, + GameDesignPublicationOperation operation, + VersionAssetPublicationRepository.ExportSnapshot snapshot) + throws Exception { + var requested = candidate(snapshot); + var mapper = new ObjectMapper(); + String artifactDigestsJson = mapper.writeValueAsString(requested.manifest().artifactDigests()); + String objectProofsJson = historicalObjectProofsJson(requested, mapper); + String assetKeysJson = + mapper.writeValueAsString(requested.manifest().requiredManifestAssetKeys()); + write.executeWithoutResult( + status -> + dsl.execute( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, exported_version_number, artifact_state, state_epoch, " + + "last_workflow_id, exported_manifest_asset_keys_json) " + + "VALUES (?, ?, ?, 'STAGED', 1, ?, '[]')", + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + var updated = + write.execute( + status -> + dsl.execute( + "UPDATE version_asset_artifact SET manifest_hash = ?, manifest_schema_version = ?, " + + "artifact_digests_json = ?, published_object_proofs_json = ?, " + + "candidate_snapshot_version_id = ?, candidate_public_base_url = ?, " + + "exported_manifest_asset_keys_json = ?, state_epoch = state_epoch + 1, " + + "updated_at = CURRENT_TIMESTAMP " + + "WHERE tenant_id = ? AND version_id = ? AND artifact_state = 'STAGED' " + + "AND state_epoch = 1 AND manifest_schema_version IS NULL " + + "AND last_workflow_id = ?", + requested.manifest().manifestHash(), + requested.manifest().manifestSchemaVersion(), + artifactDigestsJson, + objectProofsJson, + version.getId(), + requested.publicBaseUrl(), + assetKeysJson, + game.getTenantId(), + version.getId(), + operation.workflowId())); + if (updated == null || updated != 1) { + throw new IllegalStateException("HISTORICAL_ASSET_CANDIDATE_WRITE_CONFLICT"); + } + var committed = + write.execute( + status -> readHistoricalAssetCandidate(dsl, game.getTenantId(), version, mapper)); + assertThat(committed).isEqualTo(requested); + var readback = + write.execute( + status -> readHistoricalAssetCandidate(dsl, game.getTenantId(), version, mapper)); + assertThat(readback).isEqualTo(committed); + return readback; + } + + private FrozenAssetExportCandidate readHistoricalAssetCandidate( + DSLContext dsl, String tenantId, Version version, ObjectMapper mapper) { + var row = + dsl.fetchOne( + "SELECT manifest_hash, manifest_schema_version, artifact_digests_json, " + + "published_object_proofs_json, candidate_public_base_url, " + + "exported_manifest_asset_keys_json FROM version_asset_artifact " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + version.getId()); + if (row == null) { + throw new IllegalStateException("HISTORICAL_ASSET_CANDIDATE_UNAVAILABLE"); + } + var keys = new ArrayList(); + for (var node : mapper.readTree(row.get("exported_manifest_asset_keys_json", String.class))) { + keys.add(node.textValue()); + } + var digests = new ArrayList(); + for (var node : mapper.readTree(row.get("artifact_digests_json", String.class))) { + digests.add( + new PublishedArtifactDigest( + node.get("usageKey").textValue(), + node.get("artifactKind").textValue(), + node.get("immutableObjectKey").textValue(), + node.get("contentDigest").textValue(), + node.get("contentType").textValue(), + node.get("artifactSchemaVersion").intValue())); + } + var manifest = + new ExportedAssetManifest( + row.get("manifest_hash", String.class), + row.get("manifest_schema_version", Integer.class), + keys, + digests); + var candidate = + new FrozenAssetExportCandidate( + manifest, row.get("candidate_public_base_url", String.class)); + if (!historicalObjectProofsJson(candidate, mapper) + .equals(row.get("published_object_proofs_json", String.class))) { + throw new IllegalStateException("HISTORICAL_ASSET_CANDIDATE_READBACK_CONFLICT"); + } + return candidate; + } + + private String historicalObjectProofsJson( + FrozenAssetExportCandidate candidate, ObjectMapper mapper) { + var proofs = new ArrayList>(); + for (var digest : candidate.manifest().artifactDigests()) { + proofs.add(historicalObjectProof(digest.immutableObjectKey(), digest.contentDigest())); + } + String manifestHash = candidate.manifest().manifestHash(); + proofs.add( + historicalObjectProof( + "manifests/sha256/" + manifestHash.substring("sha256:".length()), manifestHash)); + proofs.sort(Comparator.comparing(proof -> proof.get("immutableObjectKey"))); + return mapper.writeValueAsString(proofs); + } + + private Map historicalObjectProof(String objectKey, String contentDigest) { + var proof = new LinkedHashMap(); + proof.put("immutableObjectKey", objectKey); + proof.put("contentDigest", contentDigest); + return proof; + } + private static String sha256(byte[] bytes) { try { return "sha256:" @@ -1464,6 +1810,9 @@ private static void await(CountDownLatch latch) { } } + private record OperationRowSnapshot( + String rowJson, byte[] requestBytes, String requestChecksum, String rowChecksum) {} + private record Fixture( DSLContext dsl, TransactionTemplate write, @@ -1475,5 +1824,6 @@ private record Fixture( GameDesignPublicationOperationService service, GameDesignPublicationOperation operation, FrozenAssetExportCandidate candidate, + boolean historicalV1, 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 index 51996e07c8..1c8c002f4a 100644 --- 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 @@ -92,6 +92,10 @@ class RealmPolicyPublicationPostgresIntegrationTest { void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exception { Fixture fixture = fixture(true); GameDesignPublicationOperation operation = fixture.prepare(true); + var sourceCapture = + new GameDesignSourceRepository(fixture.dsl()).readCapture(operation).orElseThrow(); + assertThat(sourceCapture.asset().orElseThrow().snapshot().items()).isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isZero(); fixture.writePublish(operation, false); var originalOwnerRead = fixture.operations().read(operation.workflowId()).orElseThrow(); @@ -619,7 +623,7 @@ private static void assertRejectedHeaderClonesPreserveOriginal( original, "operation_bytes", "existing.operation_bytes || decode('00', 'hex')", - terminalBindingError); + "Publication v2 schema, exact frame count or inventory digest invalid"); assertRejectedHeaderClonePreservesOriginal( fixture, original, 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 b22e55d32c..278907d248 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 @@ -63,7 +63,6 @@ void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws E 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); @@ -91,7 +90,9 @@ void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws E assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBeforeLatest); assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBeforeLatest); - assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyBeforeLatest); + // Later selected-publication migrations intentionally replace the guard body while retaining + // its identity. Keep the schema-specific insert/reject assertions above and the current-guard + // behavior proof below as the semantic checks across that migration boundary. assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 3); } @@ -160,7 +161,6 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); - String functionBodyAfterSelectorMigration = selectorFunctionBody(jdbc); migrate(dataSource, schema, null); assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); @@ -168,7 +168,9 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBefore); assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBefore); - assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyAfterSelectorMigration); + // V1020 deliberately replaces the guard body with the current full semantic owner guard. + // The identity checks above and both migration-boundary insert/reject cases prove continuity + // without freezing a superseded PL/pgSQL implementation detail. assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 4); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index bf32a81572..0dc3cd7287 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -8,7 +8,13 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.IsolatedAssetSourceOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; @@ -18,8 +24,11 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; class VersionAssetExportSnapshotIntegrationTest { private static final String USAGE_KEY = "logo.bin"; @@ -46,7 +55,7 @@ void rejectsWellFormedDigestThatDoesNotMatchMappedSourceBytes() { assertThatThrownBy(() -> insertItem(fixture, wrongDigest, CONTENT_TYPE, SOURCE_BYTES.length)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("source metadata does not match game_assets"); + .hasStackTraceContaining("export item differs from synchronized ordinary source"); } @Test @@ -62,12 +71,61 @@ void acceptsDigestOfExactMappedSourceBytes() { .isEqualTo(1); } + @Test + void freezesOnlyTheSynchronizedAssetProjectionAndDeniesDirectAssociation() { + Fixture fixture = fixture(); + var repository = new VersionAssetPublicationRepository(fixture.dsl); + assertThatThrownBy( + () -> + repository.associateDraftAsset( + fixture.tenantId, fixture.versionId, fixture.assetId, "RESOURCE")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synchronized ASSET_REFERENCE"); + var snapshot = + fixture.dsl.transactionResult( + configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().getFirst().usageKey()).isEqualTo(USAGE_KEY); + assertThat(snapshot.items().getFirst().contentDigest()).isEqualTo(sha256(SOURCE_BYTES)); + assertThat(repository.readFrozenAssetBytes(fixture.tenantId, 1, snapshot.items().getFirst())) + .containsExactly(SOURCE_BYTES); + } + + @Test + void rejectsRenamingSynchronizedSourceBeforePersistingSnapshot() { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_assets SET file_name = ? WHERE tenant_id = ? AND id = ?", + "renamed-logo.bin", + fixture.tenantId, + fixture.assetId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ordinary asset source bytes are immutable from source history"); + assertThat( + fixture.dsl.fetchCount( + DSL.table("version_asset_export_snapshot"), + DSL.field("tenant_id").eq(fixture.tenantId), + DSL.field("version_id").eq(fixture.versionId))) + .isZero(); + assertThat( + fixture.dsl.fetchCount( + DSL.table("version_asset_export_item"), + DSL.field("tenant_id").eq(fixture.tenantId), + DSL.field("version_id").eq(fixture.versionId))) + .isZero(); + } + @Test void rejectsRenamedMappedSourceBeforePersistingSnapshot() { Fixture fixture = fixture(); - // V37 normally prevents this drift with its source-name foreign key. Drop that one guard in - // this isolated schema to prove the repository still rejects a stale/legacy mapping itself. + // Disable the two earlier database guards in this isolated schema to exercise the + // repository freeze path's exact source readback against a stale projected mapping. fixture.dsl.execute("ALTER TABLE version_asset DROP CONSTRAINT fk_version_asset_asset_name"); + fixture.dsl.execute("DROP TRIGGER ordinary_asset_byte_history_guard ON game_assets"); fixture.dsl.execute( "UPDATE game_assets SET file_name = ? WHERE tenant_id = ? AND id = ?", "renamed-logo.bin", @@ -82,7 +140,7 @@ void rejectsRenamedMappedSourceBeforePersistingSnapshot() { .freezeOrReadSnapshot(fixture.tenantId, 1); })) .isInstanceOf(IllegalStateException.class) - .hasMessage("Version asset usage key no longer matches its source file name"); + .hasMessage("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); assertThat( fixture.dsl.fetchCount( DSL.table("version_asset_export_snapshot"), @@ -103,14 +161,14 @@ void retainsSourceTypeSizeAndExactMappingChecks() { assertThatThrownBy( () -> insertItem(wrongType, sha256(SOURCE_BYTES), "image/png", SOURCE_BYTES.length)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("source metadata does not match game_assets"); + .hasStackTraceContaining("export item differs from synchronized ordinary source"); Fixture wrongSize = fixture(); assertThatThrownBy( () -> insertItem(wrongSize, sha256(SOURCE_BYTES), CONTENT_TYPE, SOURCE_BYTES.length + 1L)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("source metadata does not match game_assets"); + .hasStackTraceContaining("export item differs from synchronized ordinary source"); Fixture wrongMapping = fixture(); assertThatThrownBy( @@ -127,7 +185,7 @@ void retainsSourceTypeSizeAndExactMappingChecks() { sha256(SOURCE_BYTES), SOURCE_BYTES.length)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("source metadata does not match game_assets"); + .hasStackTraceContaining("export item differs from synchronized ordinary source"); } @Test @@ -187,8 +245,7 @@ void preservesFrozenSourceBytesAgainstUpdateAfterMetadataSnapshotRead() { fixture.tenantId, fixture.assetId)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining( - "game asset source rows are immutable while a frozen version snapshot references them"); + .hasStackTraceContaining("ordinary asset source bytes are immutable from source history"); assertThat(repository.readFrozenSnapshot(fixture.tenantId, 1).items()) .containsExactly(selection); assertThat(repository.readFrozenAssetBytes(fixture.tenantId, 1, selection)) @@ -196,8 +253,35 @@ void preservesFrozenSourceBytesAgainstUpdateAfterMetadataSnapshotRead() { } @Test - void rejectsOversizedFrozenSourceFromMetadataBeforePayloadRead() { - Fixture fixture = fixture(); + void rejectsOversizedCurrentSourceBeforePersistingExportSnapshot() { + byte[] oversized = new byte[(int) VersionAssetPublicationRepository.MAX_SOURCE_ASSET_BYTES + 1]; + Fixture fixture = fixture(oversized); + + assertThatThrownBy( + () -> + fixture.dsl.transaction( + configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_TOO_LARGE"); + assertThat( + fixture.dsl.fetchCount( + DSL.table("version_asset_export_snapshot"), + DSL.field("tenant_id").eq(fixture.tenantId), + DSL.field("version_id").eq(fixture.versionId))) + .isZero(); + assertThat( + fixture.dsl.fetchCount( + DSL.table("version_asset_export_item"), + DSL.field("tenant_id").eq(fixture.tenantId), + DSL.field("version_id").eq(fixture.versionId))) + .isZero(); + } + + @Test + void rejectsOversizedRetainedFrozenSourceFromMetadataBeforePayloadRead() { + Fixture fixture = fixture(MigrationVersion.fromVersion("49.1")); byte[] oversized = new byte[(int) VersionAssetPublicationRepository.MAX_SOURCE_ASSET_BYTES + 1]; fixture.dsl.transaction( configuration -> { @@ -217,6 +301,7 @@ void rejectsOversizedFrozenSourceFromMetadataBeforePayloadRead() { fixture.tenantId, fixture.versionId); }); + migrateToLatest(fixture); assertThatThrownBy( () -> @@ -320,10 +405,18 @@ void retainedPreV50CandidateWithoutOriginAllowsLifecycleUpdateButCannotBeBackfil } private Fixture fixture() { - return fixture(null); + return fixture(null, SOURCE_BYTES); + } + + private Fixture fixture(byte[] sourceBytes) { + return fixture(null, sourceBytes); } private Fixture fixture(MigrationVersion target) { + return fixture(target, SOURCE_BYTES); + } + + private Fixture fixture(MigrationVersion target, byte[] sourceBytes) { String schema = "game_design_export_snapshot_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = postgres.dataSource(); dataSource.setSchema(schema); @@ -343,6 +436,45 @@ private Fixture fixture(MigrationVersion target) { DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); String tenantId = UUID.randomUUID().toString(); + if (target == null) { + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return write.execute( + status -> { + var game = new Game(); + game.setTenantId(tenantId); + game.setName("Export snapshot test"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + Long assetId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " + + "VALUES (?, ?, ?, ?) RETURNING id", + tenantId, + USAGE_KEY, + CONTENT_TYPE, + sourceBytes), + "asset insert returned no row") + .get(0, Long.class); + IsolatedAssetSourceOwnerSetup.upsert( + dsl, + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()), + assetId, + USAGE_KEY); + return new Fixture(dsl, tenantId, version.getId(), assetId, dataSource, schema); + }); + } Long gameId = Objects.requireNonNull( dsl.fetchOne( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index f2b29987ce..8a8b966cab 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Map; import java.util.UUID; @@ -1273,6 +1274,15 @@ void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .satisfies( + failure -> { + assertThat(failure).isInstanceOf(SQLException.class); + assertThat(((SQLException) failure).getSQLState()).isEqualTo("0A000"); + }) + .hasMessageContaining("cannot truncate a table referenced in a foreign key constraint"); + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor CASCADE")) .isInstanceOf(DataAccessException.class) .rootCause() .hasMessageContaining("launch descriptors are immutable"); 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 19bbf05c41..a8a62294f9 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 @@ -1010,10 +1010,22 @@ private SelectedPublicationFixture selectedPublicationFixture( persisted.getIdentitySourceGameRowId(), persisted.getIdentitySourceGameTenantKey(), persisted.getIdentitySourceProvenanceKind()); + 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); try { GameDesignPublicationOperation operation = IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( - dsl, target, persisted.getVersionStateEpoch(), "ISOLATED publication proof"); + dsl, + target, + persisted.getVersionStateEpoch(), + "ISOLATED publication proof", + List.of( + new IsolatedPublicationOwnerSetup.OrdinaryAsset( + persistedAsset.getId(), "fixture.bin"))); return new SelectedPublicationFixture(persisted, operation); } catch (Exception failure) { throw new IllegalStateException("Selected publication fixture setup failed", failure); @@ -1083,14 +1095,6 @@ private ExportedAssetManifest recordFixtureCandidate( .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( 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 index 78b7d4afa8..7e386d4356 100644 --- 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 @@ -7,6 +7,7 @@ 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.AssetSnapshot; import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; @@ -14,25 +15,40 @@ class GameDesignReviewedBaseEvidenceTest { @Test - void genesisBindsOriginalPairedReceiptTargetAndCreationWitnessWithoutCommit() { + void genesisBindsPolicyCommandAndDistinctAssetBaselineWithoutCommit() { 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 assetReceipt = UUID.randomUUID(); + var genesis = genesis(target, receipt, "11", assetReceipt); 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.canonicalBytes()).contains(genesis.asset().canonicalBytes()); assertThat(evidence.digest()) .isEqualTo(DraftAuthorizationFenceBinding.digest(evidence.canonicalBytes())); assertThat(evidence).isEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis)); assertThat(evidence) - .isNotEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis(target, receipt, "12"))); + .isNotEqualTo( + GameDesignReviewedBaseEvidence.genesis( + genesis(target, receipt, "12", genesis.asset().receiptId()))); + assertThat(evidence) + .isNotEqualTo( + GameDesignReviewedBaseEvidence.genesis( + genesis(target, UUID.randomUUID(), "11", genesis.asset().receiptId()))); assertThat(evidence) .isNotEqualTo( - GameDesignReviewedBaseEvidence.genesis(genesis(target, UUID.randomUUID(), "11"))); + GameDesignReviewedBaseEvidence.genesis( + genesis(target, receipt, "11", UUID.randomUUID()))); + assertThatThrownBy( + () -> + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis(genesis.policy(), genesis.command()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("GAME_DESIGN_SOURCE_ASSET_GENESIS_UNAVAILABLE"); byte[] returned = evidence.canonicalBytes(); returned[0] ^= 1; assertThat(returned).isNotEqualTo(evidence.canonicalBytes()); @@ -53,9 +69,10 @@ void readbackRejectsChangedDigestAndDefensivelyCopiesBytes() { } private static GameDesignSourceRepository.Genesis genesis( - TargetProof target, UUID receipt, String witness) { + TargetProof target, UUID receipt, String witness, UUID assetReceipt) { return new GameDesignSourceRepository.Genesis( new RealmPolicyGenesis(target, receipt, witness), - new CommandSource.NewDraftGenesisReceipt(target, receipt, witness)); + new CommandSource.NewDraftGenesisReceipt(target, receipt, witness), + java.util.Optional.of(new AssetSnapshot.Genesis(target, assetReceipt, 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 index 9a160c7cbf..ab89cd4626 100644 --- 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 @@ -12,6 +12,7 @@ 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.AssetSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.publication.CommandApplication; import net.firedevops.firemud.gamedesign.publication.CommandSnapshot; @@ -130,6 +131,11 @@ void mixedControlPlaneCommitReturnsCommandEvidenceWithoutTakingOwnerOutcomeOwner "1", UUID.randomUUID(), "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"main\",\"policy\":{}}"); + var assetRevision = + revision( + "2", + UUID.randomUUID(), + AssetSource.upsertPayload("41", "map", AssetSource.Requiredness.REQUIRED)); var policyScope = new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -141,11 +147,12 @@ void mixedControlPlaneCommitReturnsCommandEvidenceWithoutTakingOwnerOutcomeOwner var binding = binding( commitId, - List.of(commandRevision, policyRevision), - List.of(commandScope("0"), policyScope)); + List.of(commandRevision, policyRevision, assetRevision), + List.of(commandScope("0"), policyScope, assetScope("0"))); var mutations = CommandSource.mutations(binding); assertThat(mutations).hasSize(1); + assertThat(AssetSource.mutations(binding)).hasSize(1); assertThat(CommandSource.hasRealmPolicyRevision(binding)).isTrue(); var snapshot = new CommandSnapshot( @@ -171,6 +178,19 @@ void mixedControlPlaneCommitReturnsCommandEvidenceWithoutTakingOwnerOutcomeOwner assertThat(ByteBuffer.wrap(applicationBytes).getInt(4 + schemaBytes.length)).isZero(); } + @Test + void unknownOwnerRevisionKindRemainsClosedForCommandClassification() { + var unknownRevision = revision("0", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); + var binding = binding(UUID.randomUUID(), List.of(unknownRevision), List.of(commandScope("0"))); + + assertThatThrownBy(() -> CommandSource.mutations(binding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design command source revision kind"); + assertThatThrownBy(() -> CommandSource.hasRealmPolicyRevision(binding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design command source revision kind"); + } + @Test void rejectsAmbiguousAliasesAndKeepsTheEntireEffectiveSet() { var first = definition("look", "inspect", UUID.randomUUID(), UUID.randomUUID(), "0"); @@ -272,6 +292,16 @@ private static DraftCommitBinding.AffectedUnit commandScope(String epoch) { epoch); } + private static DraftCommitBinding.AffectedUnit assetScope(String epoch) { + return new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + TARGET.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + epoch); + } + private static DraftCommitBinding binding( UUID commitId, List revisions, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationHistoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationHistoryTest.java new file mode 100644 index 0000000000..a4a5cee489 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationHistoryTest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +/** Original-byte wrapper proof with stipulated source values; no owner production or SQL proof. */ +class GameDesignPublicationOperationHistoryTest { + @Test + void retainedV1KeepsOriginalBytesAndReadSelectorsWithoutCompleteInventoryAuthority() + throws Exception { + var fresh = fresh(); + var original = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(original, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(original, fresh.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(original, fresh.world().canonicalBytes()); + byte[] bytes = original.toByteArray(); + var historical = GameDesignPublicationOperation.fromStored(bytes); + + assertThat(historical.canonicalBytes()).containsExactly(bytes); + assertThat(historical.account().canonicalBytes()) + .containsExactly(fresh.account().canonicalBytes()); + assertThat(historical.world().canonicalBytes()).containsExactly(fresh.world().canonicalBytes()); + assertThat(historical.workflowId()).isEqualTo(fresh.workflowId()); + assertThat(historical.tenantKey()).isEqualTo(fresh.tenantKey()); + assertThat(historical.versionId()).isEqualTo(fresh.versionId()); + assertThat(historical.selectionDigest()).isEqualTo(fresh.selectionDigest()); + assertThat(historical).isEqualTo(GameDesignPublicationOperation.fromStored(bytes)); + assertThat(historical.hashCode()) + .isEqualTo(GameDesignPublicationOperation.fromStored(bytes).hashCode()); + assertThat(historical).isNotEqualTo(fresh); + assertThatThrownBy(historical::inventory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); + bytes[0] ^= 1; + assertThat(historical.canonicalBytes()).containsExactly(original.toByteArray()); + } + + @Test + void freshV2RoundtripRequiresActualCompleteTypedInventory() throws Exception { + var fresh = fresh(); + var read = GameDesignPublicationOperation.fromStored(fresh.canonicalBytes()); + assertThat(read.canonicalBytes()).containsExactly(fresh.canonicalBytes()); + assertThat(read.inventory().canonicalBytes()) + .containsExactly(fresh.inventory().canonicalBytes()); + assertThat(read).isEqualTo(fresh); + assertThatThrownBy( + () -> new GameDesignPublicationOperation(fresh.account(), fresh.world(), null)) + .isInstanceOf(NullPointerException.class); + } + + private static GameDesignPublicationOperation fresh() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } +} 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 index 3a0b00d480..67725f6824 100644 --- 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 @@ -7,11 +7,36 @@ import java.util.UUID; import java.util.stream.IntStream; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; class RealmPolicySourceTest { + @Test + void policyClassifierRecognizesKnownSiblingOwnersAndRejectsUnknownKinds() { + var policy = + policyRevision( + "0", + UUID.randomUUID(), + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"main\",\"policy\":{}}"); + var command = + policyRevision("1", UUID.randomUUID(), "{\"revisionKind\":\"COMMAND_DEFINITION\"}"); + var asset = + policyRevision( + "2", + UUID.randomUUID(), + AssetSource.upsertPayload("41", "map", AssetSource.Requiredness.REQUIRED)); + var unknown = policyRevision("3", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); + + assertThat(RealmPolicySource.isPolicyRevision(policy)).isTrue(); + assertThat(RealmPolicySource.isPolicyRevision(command)).isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(asset)).isFalse(); + assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design owner revision kind"); + } + @Test void draftPolicyStateCanBeEmptyOrIncompleteWithoutPublicationCardinality() { var empty = new RealmPolicySnapshot(binding(), "0", List.of()); diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java index 0e887b49f4..c0febd630d 100644 --- a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -46,6 +46,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @@ -146,7 +147,11 @@ public static Fixture fixture( var world = new WorldPublishedStartLocationEvidence( worldRequest, receipt, committed.fullBinding(), committed.result()); - var operation = new GameDesignPublicationOperationBinding(selectionAccount(selection), world); + var account = selectionAccount(selection); + // Explicit stipulated consumer input; this fixture does not execute World's inventory producer. + var operation = + new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); var release = release(operation, versionNumber); var terminal = new GameDesignPublicationTerminalEvidence( diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index c3da9c94a7..39b564782a 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -13,6 +13,7 @@ firemudJooq { } dependencies { + testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(libs.grpc.inprocess) testImplementation(libs.grpc.netty.shaded) testImplementation(testFixtures(project(":logging-admin-service"))) diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java index bfbbd87dd8..1c9e8c30eb 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.gamesession.v1.StopSessionResponse; import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** gRPC client for communicating with the Game Session Service. */ @Component @@ -91,12 +92,14 @@ public StopSessionResponse stopSession(long sessionId) { */ public StartSessionOwnerHandoffResult authorizeStartSession( TransientOwnerExecutionHandoff handoff) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(handoff, "durable Logging owner handoff is required"); StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); String reference = handoff.accountResponse().operatorAuthorizationReference(); byte[] tupleBytes = tuple.canonicalBytes(); if (tupleBytes.length == 0 || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || reference == null || !OPAQUE_OPERATOR_REFERENCE.matcher(reference).matches() || !tuple .authenticatedWorkloadIdentity() @@ -138,6 +141,14 @@ public StartSessionOwnerHandoffResult authorizeStartSession( return validateOwnerHandoffResponse(tuple, response); } + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Session owner handoff requires no ambient SQL or synchronization"); + } + } + private void requireFileBackedMtls() { FileBackedGrpcMtlsPolicy.require( transportTlsProperties, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java index 22eca3e89a..66aa5e8e7a 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -6,6 +6,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -31,6 +32,7 @@ import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Explicitly initialized, typed Logging & Admin client for Account's StartSession issue/recover @@ -42,6 +44,12 @@ public class StartSessionOperatorAuthorizationClient StartSessionOperatorAuthorizationServiceGrpc .StartSessionOperatorAuthorizationServiceBlockingStub> { private static final int MAX_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_REQUEST_BYTES = MAX_TUPLE_BYTES + 16 * 1_024 + 1_024; + private static final int MAX_RESPONSE_BYTES = + StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2_048; + private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; private static final int MAX_REFERENCE_BYTES = 128; private static final long RPC_DEADLINE_SECONDS = 5L; @@ -109,6 +117,8 @@ protected String defaultTarget() { buildStub(io.grpc.ManagedChannel channel) { return applyStubCustomizer( StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) .withCompression("gzip")); } @@ -120,6 +130,7 @@ public AuthorizationReference issueHuman( long reservationClaimFence, UUID currentClaimOwnerId, long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); byte[] tupleBytes = canonicalTupleBytes(tuple); requireVisibleAsciiToken(controlUiJwt); requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); @@ -133,10 +144,17 @@ public AuthorizationReference issueHuman( .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) .setCurrentClaimFence(currentClaimFence) .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } IssueHumanOperatorAuthorizationReferenceResponse response = requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .issueHumanOperatorAuthorizationReference(request); + if (response == null || response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } return validateResponse( response.getOperatorAuthorizationReference(), response.getAuthorizationReferenceFingerprint(), @@ -160,6 +178,7 @@ public AuthorizationReference recover( long reservationClaimFence, UUID currentClaimOwnerId, long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); byte[] tupleBytes = canonicalTupleBytes(tuple); requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); @@ -171,10 +190,17 @@ public AuthorizationReference recover( .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) .setCurrentClaimFence(currentClaimFence) .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } RecoverOperatorAuthorizationReferenceResponse response = requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .recoverOperatorAuthorizationReference(request); + if (response == null || response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } return validateResponse( response.getOperatorAuthorizationReference(), response.getAuthorizationReferenceFingerprint(), @@ -255,9 +281,13 @@ private AuthorizationReference validateResponse( throw malformedResponse(); } Instant expiresAt = exactExpiry(expiryTimestamp); - if (!expiresAt.isAfter(clock.instant())) { + Instant now = clock.instant(); + if (!expiresAt.isAfter(now)) { throw new IllegalStateException("Account authorization response is expired"); } + if (expiresAt.isAfter(now.plus(MAX_REFERENCE_LIFETIME))) { + throw malformedResponse(); + } StartSessionAuthorityEvidenceBundle bundle = StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundle); bundle.requireTupleBinding(tuple); @@ -348,6 +378,14 @@ private static void requireVisibleAsciiToken(String token) { } } + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account authorization requires no ambient SQL or synchronization"); + } + } + private static void requireOwnerFence(UUID owner, long fence, String field) { if (owner == null || owner.equals(new UUID(0L, 0L)) || fence <= 0L) { throw new IllegalArgumentException(field + " and positive fence are required"); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java index 53bcb79115..22ad374853 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java @@ -58,7 +58,8 @@ public StartSessionOperatorAuthorizationClient startSessionOperatorAuthorization @Bean public StartSessionAuthorizationCoordinator startSessionAuthorizationCoordinator( StartSessionPreAuthorizationReservationService reservations, - StartSessionOperatorAuthorizationClient accountClient) { - return new StartSessionAuthorizationCoordinator(reservations, accountClient); + StartSessionOperatorAuthorizationClient accountClient, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new StartSessionAuthorizationCoordinator(workloadNamespace, reservations, accountClient); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java index 51a4282ad7..6b243be3df 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -1,21 +1,43 @@ package net.firedevops.firemud.loggingadmin.operator; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizationCompletion; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimHandle; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionTransition; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.PendingTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; /** * Coordinates Account authorization and durably records the owner handoff without activating an @@ -28,41 +50,118 @@ * logged here. */ public final class StartSessionAuthorizationCoordinator { + private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final JsonMapper JWT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> JSON_OBJECT = new TypeReference<>() {}; + + private final String configuredNamespace; private final StartSessionPreAuthorizationReservationService reservations; private final StartSessionOperatorAuthorizationClient accountClient; public StartSessionAuthorizationCoordinator( + String configuredNamespace, StartSessionPreAuthorizationReservationService reservations, StartSessionOperatorAuthorizationClient accountClient) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("A valid configured workload namespace is required"); + } + this.configuredNamespace = configuredNamespace; this.reservations = Objects.requireNonNull(reservations, "reservation service is required"); this.accountClient = Objects.requireNonNull(accountClient, "Account client is required"); } + /** Derives the original actor from the current authenticated tenant-admin request context. */ + public Result begin( + String controlPlaneRequestId, + StartSessionOperatorAction action, + String originalControlUiJwt) { + requireNoAmbientSqlOrSynchronization(); + Objects.requireNonNull(action, "typed StartSession action is required"); + String stableRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + requireConfiguredNamespace(action); + requireCompactJwtEnvelope(originalControlUiJwt); + // The verified Logging context binds the claimed original actor, but Account alone validates + // the forwarded ControlUI token's current authorization and signature. + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + stableRequestId, action); + return issueHuman(tuple, originalControlUiJwt); + } + /** Begins human issuance only for the first reservation owner that wins AUTHORIZATION_PENDING. */ public Result issueHuman( StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); + requireCompactJwtEnvelope(controlUiJwt); + StartSessionPreAuthorizationReservationTuple currentTuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + tuple.controlPlaneRequestId(), tuple.action()); + if (!currentTuple.canonicalJson().equals(tuple.canonicalJson())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + return issueHumanFromCurrentContext(currentTuple, controlUiJwt); + } + + private Result issueHumanFromCurrentContext( + StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { Acquisition acquisition = reservations.acquire(tuple); + Snapshot acquiredSnapshot = acquisition.snapshot(); + requireSnapshotTuple(acquiredSnapshot, tuple); if (!acquisition.newlyAcquired()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, acquiredSnapshot); } ClaimHandle claim = acquisition.claim(); - PendingTransition pending = reservations.markAuthorizationPending(claim); + if (claim == null || !claimMatchesOriginalReservation(claim, tuple)) { + return Result.outcomeUnknown(acquiredSnapshot, PendingReason.RESERVATION_CLAIM_MISMATCH); + } + + PendingTransition pending; + try { + pending = reservations.markAuthorizationPending(claim); + } catch (RuntimeException transitionFailure) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + if (pending == null || pending.snapshot() == null) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + Snapshot pendingSnapshot = pending.snapshot(); + requireSnapshotTuple(pendingSnapshot, tuple); if (!pending.mayDispatchAccountAuthorization()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, pendingSnapshot); + } + if (!isExactPendingSnapshot(pendingSnapshot, tuple, claim)) { + return Result.outcomeUnknown( + pendingSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); } ClaimEvidence claimEvidence = claim.claimEvidence(); - AuthorizationReference accountResponse = - accountClient.issueHuman( - sharedTuple(tuple), - controlUiJwt, - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - claimEvidence.currentClaimOwnerId(), - claimEvidence.currentClaimFence()); - return persistExactAccountResponse(tuple, claim, accountResponse); + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.issueHuman( + sharedTuple(tuple), + controlUiJwt, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown(pendingSnapshot, PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse(tuple, claim, accountResponse, pendingSnapshot); } /** Issues the human reference and forwards only this invocation's durable owner-pending win. */ @@ -76,22 +175,45 @@ public OwnerDispatchResult issueHumanAndDispatch( /** Recovers only the original issuance response under a fresh read-only recovery claim. */ public Result recover(StartSessionPreAuthorizationReservationTuple tuple) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); Optional acquired = reservations.acquireAuthorizationRecoveryClaim(tuple); if (acquired.isEmpty()) { return Result.recoveryUnavailable(); } - ClaimHandle claim = acquired.orElseThrow().claim(); + RecoveryAcquisition recovery = acquired.orElseThrow(); + requireSnapshotTuple(recovery.snapshot(), tuple); + ClaimHandle claim = recovery.claim(); ClaimEvidence claimEvidence = claim.claimEvidence(); - AuthorizationReference accountResponse = - accountClient.recover( - sharedTuple(tuple), - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - claimEvidence.currentClaimOwnerId(), - claimEvidence.currentClaimFence()); - return persistExactAccountResponse(tuple, claim, accountResponse); + if (!claim.isRecoveryLookupOnly() + || !tuple.canonicalJson().equals(claim.tuple().canonicalJson()) + || !tuple.mutationDigest().equals(claim.mutationDigest()) + || recovery.snapshot().claimPurpose() != claim.purpose() + || recovery.snapshot().claimState() != ClaimState.ACTIVE + || recovery.snapshot().phase() != Phase.ACCOUNT_AUTHORIZATION + || recovery.snapshot().claimFence() != claimEvidence.currentClaimFence() + || recovery.snapshot().reservationClaimFence() != claimEvidence.reservationClaimFence() + || claimEvidence.reservationOwnerId().equals(claimEvidence.currentClaimOwnerId()) + || claimEvidence.currentClaimFence() <= claimEvidence.reservationClaimFence()) { + return Result.outcomeUnknown(recovery.snapshot(), PendingReason.RESERVATION_CLAIM_MISMATCH); + } + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.recover( + sharedTuple(tuple), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown( + acquired.orElseThrow().snapshot(), PendingReason.ACCOUNT_RECOVERY_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse( + tuple, claim, accountResponse, acquired.orElseThrow().snapshot()); } /** Recovers the original reference and forwards only a newly persisted owner-pending handoff. */ @@ -118,39 +240,372 @@ private static OwnerDispatchResult dispatchOwnerPending( private Result persistExactAccountResponse( StartSessionPreAuthorizationReservationTuple tuple, ClaimHandle claim, - AuthorizationReference accountResponse) { - Objects.requireNonNull(accountResponse, "validated Account response is required"); - StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple = - accountResponse.postAuthorizationTuple(); - ClaimEvidence claimEvidence = claim.claimEvidence(); - StartSessionPostAuthorizationExecutionTuple expectedTuple = - StartSessionPostAuthorizationExecutionTuple.createHuman( - sharedTuple(tuple), - accountResponse.authenticatedLoggingWorkloadIdentity(), - accountResponse.authorizationReferenceFingerprint(), - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - accountResponse.authorityEvidenceBundle(), - accountResponse.bundleReference()); - if (!MessageDigest.isEqual( - expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes())) { - throw new IllegalArgumentException( - "Account post-authorization tuple differs from its authorization response"); + AuthorizationReference accountResponse, + Snapshot lastKnownSnapshot) { + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple; + String transientReference; + try { + if (accountResponse == null) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + transientReference = accountResponse.operatorAuthorizationReference(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + if (transientReference == null || !OPAQUE_REFERENCE.matcher(transientReference).matches()) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + String expectedWorkloadIdentity = + "spiffe://firemud/ns/" + configuredNamespace + "/sa/logging-admin-service"; + if (!expectedWorkloadIdentity.equals( + accountResponse.authenticatedLoggingWorkloadIdentity())) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + StartSessionPostAuthorizationExecutionTuple expectedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + sharedTuple(tuple), + accountResponse.authenticatedLoggingWorkloadIdentity(), + accountResponse.authorizationReferenceFingerprint(), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + accountResponse.authorityEvidenceBundle(), + accountResponse.bundleReference()); + postAuthorizationTuple = accountResponse.postAuthorizationTuple(); + if (postAuthorizationTuple == null + || !MessageDigest.isEqual( + expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes()) + || !isExactAccountResult(tuple, claimEvidence, accountResponse, postAuthorizationTuple)) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + } catch (RuntimeException invalidResponse) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + + AuthorizationCompletion completion; + try { + completion = reservations.completeAuthorization(claim, postAuthorizationTuple); + } catch (RuntimeException localCompletionFailure) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); + } + if (completion == null || completion.snapshot() == null) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); } - AuthorizationCompletion completion = - reservations.completeAuthorization(claim, postAuthorizationTuple); if (!completion.transitioned()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, completion.snapshot().reservationSnapshot()); + } + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizedSnapshot completedSnapshot = completion.snapshot(); + if (!isExactAuthorizedSnapshot( + completedSnapshot, tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.LOCAL_COMPLETION_RESULT_MISMATCH); } + + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException readbackFailure) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null + || readback.isEmpty() + || !sameAuthorizedSnapshot(completedSnapshot, readback.orElseThrow()) + || !isExactAuthorizedSnapshot( + readback.orElseThrow(), tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_MISMATCH); + } + OwnerExecutionHandoff handoff = new OwnerExecutionHandoff(UUID.randomUUID()); - OwnerExecutionTransition ownerTransition = - reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + OwnerExecutionTransition ownerTransition; + try { + ownerTransition = reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + } catch (RuntimeException ownerTransitionFailure) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } + if (ownerTransition == null || ownerTransition.snapshot() == null) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } if (!ownerTransition.mayDispatch()) { - return Result.alreadyInProgress(); + return Result.alreadyInProgress(ownerTransition.snapshot().reservationSnapshot(), readback); + } + if (!isExactOwnerPendingSnapshot( + ownerTransition.snapshot(), tuple, claim, claimEvidence, postAuthorizationTuple, handoff)) { + return Result.outcomeUnknown( + ownerTransition.snapshot().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_RESULT_MISMATCH, + readback); } return Result.ownerExecutionPending( new TransientOwnerExecutionHandoff( - ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple)); + ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple), + ownerTransition.snapshot().reservationSnapshot(), + readback); + } + + private Result observeExisting( + StartSessionPreAuthorizationReservationTuple tuple, Snapshot acquisitionSnapshot) { + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException unavailable) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback.isPresent()) { + AuthorizedSnapshot existing = readback.orElseThrow(); + if (!isBoundAuthorizedSnapshot(existing, tuple)) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(existing.reservationSnapshot(), readback); + } + if (acquisitionSnapshot.state() == State.AUTHORIZED + || acquisitionSnapshot.state() == State.OWNER_EXECUTION_PENDING) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(acquisitionSnapshot, Optional.empty()); + } + + private boolean isExactAccountResult( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimEvidence claimEvidence, + AuthorizationReference response, + StartSessionPostAuthorizationExecutionTuple postTuple) { + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()); + if (!response.expiresAt().equals(bundle.expiresAt()) + || !tuple.canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !tuple.controlPlaneRequestId().equals(postTuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(postTuple.mutationDigest()) + || !"human_operator".equals(postTuple.issuanceKind()) + || !claimEvidence.reservationOwnerId().equals(postTuple.reservationOwnerId()) + || claimEvidence.reservationClaimFence() != postTuple.reservationClaimFence()) { + return false; + } + bundle.requireTupleBinding(postTuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(postTuple.bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean claimMatchesOriginalReservation( + ClaimHandle claim, StartSessionPreAuthorizationReservationTuple tuple) { + ClaimEvidence evidence = claim.claimEvidence(); + return tuple.canonicalJson().equals(claim.tuple().canonicalJson()) + && tuple.mutationDigest().equals(claim.mutationDigest()) + && claim.purpose() == ClaimPurpose.ORIGINAL + && evidence.reservationOwnerId().equals(evidence.currentClaimOwnerId()) + && evidence.reservationClaimFence() == evidence.currentClaimFence() + && evidence.reservationClaimFence() > 0L; + } + + private static boolean isExactPendingSnapshot( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple, ClaimHandle claim) { + ClaimEvidence evidence = claim.claimEvidence(); + return snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimPurpose() == claim.purpose() + && snapshot.reservationClaimFence() == evidence.reservationClaimFence() + && snapshot.claimFence() == evidence.currentClaimFence() + && tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + && tuple.mutationDigest().equals(snapshot.mutationDigest()); + } + + private static boolean isExactAuthorizedSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() == State.AUTHORIZED + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && snapshot.handoff() == null + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()); + } + + private static boolean isExactOwnerPendingSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple, + OwnerExecutionHandoff expectedHandoff) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() == State.OWNER_EXECUTION_PENDING + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()) + && expectedHandoff.equals(snapshot.handoff()); + } + + private static boolean isBoundAuthorizedSnapshot( + AuthorizedSnapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.reservationSnapshot().tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.reservationSnapshot().mutationDigest()) + || !tuple + .canonicalJson() + .equals(snapshot.postAuthorizationTuple().preAuthorizationTuple().canonicalJson()) + || !tuple + .controlPlaneRequestId() + .equals(snapshot.postAuthorizationTuple().controlPlaneRequestId()) + || !tuple.mutationDigest().equals(snapshot.postAuthorizationTuple().mutationDigest()) + || !"human_operator".equals(snapshot.postAuthorizationTuple().issuanceKind()) + || snapshot.reservationSnapshot().reservationClaimFence() + != snapshot.postAuthorizationTuple().reservationClaimFence() + || !snapshot + .reservationOwnerId() + .equals(snapshot.postAuthorizationTuple().reservationOwnerId()) + || snapshot.reservationSnapshot().state() != State.AUTHORIZED + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING + || snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() != State.AUTHORIZED + || snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING) { + return false; + } + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode( + snapshot.postAuthorizationTuple().authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(snapshot.postAuthorizationTuple().preAuthorizationTuple()); + bundle.requireReferenceBinding(snapshot.postAuthorizationTuple().bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean sameAuthorizedSnapshot( + AuthorizedSnapshot expected, AuthorizedSnapshot actual) { + return expected.reservationSnapshot().equals(actual.reservationSnapshot()) + && Arrays.equals( + expected.postAuthorizationTuple().canonicalBytes(), + actual.postAuthorizationTuple().canonicalBytes()) + && expected.reservationOwnerId().equals(actual.reservationOwnerId()) + && Objects.equals(expected.currentClaimOwnerId(), actual.currentClaimOwnerId()) + && Objects.equals(expected.handoff(), actual.handoff()); + } + + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "StartSession authorization requires no ambient SQL or synchronization"); + } + } + + private void requireConfiguredNamespace(StartSessionOperatorAction action) { + if (!configuredNamespace.equals(action.scope().targetNamespace())) { + throw new IllegalArgumentException( + "StartSession target namespace does not match the configured workload namespace"); + } + } + + private static void requireSnapshotTuple( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + /** Local envelope validation is not signature validation or current Account authorization. */ + private static void requireCompactJwtEnvelope(String token) { + if (token == null || token.isEmpty() || token.length() > MAX_CONTROL_UI_JWT_BYTES) { + throw malformedJwtEnvelope(); + } + for (int index = 0; index < token.length(); index++) { + if (token.charAt(index) > 0x7f) { + throw malformedJwtEnvelope(); + } + } + String[] segments = token.split("\\.", -1); + if (segments.length != 3 + || segments[0].isEmpty() + || segments[1].isEmpty() + || segments[2].isEmpty()) { + throw malformedJwtEnvelope(); + } + byte[] header = decodeJwtSegment(segments[0]); + byte[] claims = decodeJwtSegment(segments[1]); + byte[] signature = decodeJwtSegment(segments[2]); + if (header == null || claims == null || signature == null || signature.length == 0) { + throw malformedJwtEnvelope(); + } + requireJsonObject(header); + requireJsonObject(claims); + } + + private static byte[] decodeJwtSegment(String segment) { + if (!segment.matches("[A-Za-z0-9_-]+")) { + return null; + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + return Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(segment) + ? decoded + : null; + } catch (IllegalArgumentException malformed) { + return null; + } + } + + private static void requireJsonObject(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map object = JWT_JSON.readValue(json, JSON_OBJECT); + if (object == null) { + throw malformedJwtEnvelope(); + } + } catch (IOException | RuntimeException malformed) { + throw malformedJwtEnvelope(); + } + } + + private static IllegalArgumentException malformedJwtEnvelope() { + return new IllegalArgumentException("control-ui JWT envelope is malformed"); } private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple @@ -162,29 +617,92 @@ private Result persistExactAccountResponse( public enum Progress { OWNER_EXECUTION_PENDING, ALREADY_IN_PROGRESS, - RECOVERY_UNAVAILABLE + RECOVERY_UNAVAILABLE, + AUTHORIZATION_OUTCOME_UNKNOWN } /** Contains no response material unless this call won the durable owner-pending transition. */ - public record Result(Progress progress, TransientOwnerExecutionHandoff handoff) { - public Result { - Objects.requireNonNull(progress, "progress is required"); - if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null)) { + public static final class Result { + private final Progress progress; + private final TransientOwnerExecutionHandoff handoff; + private final Snapshot snapshot; + private final Optional authorizedReadback; + private final PendingReason pendingReason; + + private Result( + Progress progress, + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback, + PendingReason pendingReason) { + this.progress = Objects.requireNonNull(progress, "progress is required"); + this.handoff = handoff; + this.snapshot = snapshot; + this.authorizedReadback = + Objects.requireNonNull(authorizedReadback, "authorized readback is required"); + this.pendingReason = pendingReason; + if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null) + || (progress == Progress.RECOVERY_UNAVAILABLE) != (snapshot == null) + || (progress == Progress.AUTHORIZATION_OUTCOME_UNKNOWN) != (pendingReason != null)) { throw new IllegalArgumentException( - "only newly persisted owner-pending state has a handoff"); + "authorization result progress and transient material are inconsistent"); } } - private static Result ownerExecutionPending(TransientOwnerExecutionHandoff handoff) { - return new Result(Progress.OWNER_EXECUTION_PENDING, handoff); + private static Result ownerExecutionPending( + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback) { + return new Result( + Progress.OWNER_EXECUTION_PENDING, handoff, snapshot, authorizedReadback, null); } - private static Result alreadyInProgress() { - return new Result(Progress.ALREADY_IN_PROGRESS, null); + private static Result alreadyInProgress( + Snapshot snapshot, Optional authorizedReadback) { + return new Result( + Progress.ALREADY_IN_PROGRESS, + null, + Objects.requireNonNull(snapshot, "observed snapshot is required"), + authorizedReadback, + null); + } + + private static Result outcomeUnknown(Snapshot snapshot, PendingReason reason) { + return outcomeUnknown(snapshot, reason, Optional.empty()); + } + + private static Result outcomeUnknown( + Snapshot snapshot, PendingReason reason, Optional authorizedReadback) { + return new Result( + Progress.AUTHORIZATION_OUTCOME_UNKNOWN, + null, + Objects.requireNonNull(snapshot, "last known snapshot is required"), + authorizedReadback, + Objects.requireNonNull(reason, "pending reason is required")); } private static Result recoveryUnavailable() { - return new Result(Progress.RECOVERY_UNAVAILABLE, null); + return new Result(Progress.RECOVERY_UNAVAILABLE, null, null, Optional.empty(), null); + } + + public Progress progress() { + return progress; + } + + public TransientOwnerExecutionHandoff handoff() { + return handoff; + } + + public Snapshot snapshot() { + return snapshot; + } + + public Optional authorizedReadback() { + return authorizedReadback; + } + + public Optional pendingReason() { + return Optional.ofNullable(pendingReason); } @Override @@ -193,10 +711,32 @@ public String toString() { + progress + ", handoff=" + (handoff == null ? "null" : "") + + ", snapshot=" + + (snapshot == null ? "null" : "") + + ", authorizedReadbackPresent=" + + authorizedReadback.isPresent() + + ", pendingReason=" + + pendingReason + "]"; } } + public enum PendingReason { + RESERVATION_CLAIM_MISMATCH, + PENDING_TRANSITION_OUTCOME_UNKNOWN, + ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN, + ACCOUNT_RECOVERY_OUTCOME_UNKNOWN, + ACCOUNT_RESPONSE_INVALID, + LOCAL_COMPLETION_OUTCOME_UNKNOWN, + LOCAL_COMPLETION_RESULT_MISMATCH, + AUTHORIZATION_READBACK_UNKNOWN, + AUTHORIZATION_READBACK_MISMATCH, + EXISTING_AUTHORIZATION_READBACK_UNKNOWN, + EXISTING_AUTHORIZATION_READBACK_MISMATCH, + OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + OWNER_PENDING_TRANSITION_RESULT_MISMATCH + } + /** * Safe composition result: original progress and, only after dispatch, a secret-free owner echo. */ diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java index a6c8b8266f..5cc5c154d0 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java @@ -17,6 +17,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -38,6 +39,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; class GameSessionClientTest { @TempDir private Path tlsDirectory; @@ -84,7 +86,7 @@ public > T customize(T candidate) { @Test void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); - var handoff = handoff(); + TransientOwnerExecutionHandoff handoff = handoff(); StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); AuthorizeStartSessionResponse response = ownerResponse( @@ -100,8 +102,7 @@ void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception GameSessionClient.StartSessionOwnerHandoffResult result = client.authorizeStartSession(handoff); - verify(stub, times(1)) - .withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS); + verify(stub, times(1)).withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS); verify(stub, times(1)).authorizeStartSession(requestCaptor.capture()); verify(stub, never()).stopSession(any()); assertThat( @@ -132,7 +133,7 @@ void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception @Test void refusesOwnerResponseThatDoesNotEchoTheOriginalTuple() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); - var handoff = handoff(); + TransientOwnerExecutionHandoff handoff = handoff(); AuthorizeStartSessionResponse substitutedResponse = ownerResponse( handoff.postAuthorizationTuple(), @@ -190,6 +191,43 @@ void rejectsSubstitutedAccountReferenceBeforeCallingGameSession() throws Excepti verify(stub, never()).authorizeStartSession(any()); } + @Test + void refusesNullOpaqueReferenceBeforeOwnerRpc() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(handoff.accountResponse().operatorAuthorizationReference()).thenReturn(null); + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalArgumentException.class); + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void refusesOwnerHandoffInsideAmbientSqlOrSynchronizationBeforeRpc() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + GameSessionClient client = client(stub); + TransientOwnerExecutionHandoff handoff = handoff(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + verify(stub, never()).authorizeStartSession(any()); + } + @Test void surfacesTransportAmbiguityWithoutAutomaticRetryOrReferenceDisclosure() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -252,8 +290,7 @@ private static GameSessionServiceGrpc.GameSessionServiceBlockingStub mockStub() var stub = mock(GameSessionServiceGrpc.GameSessionServiceBlockingStub.class); when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); - when(stub.withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS)) - .thenReturn(stub); + when(stub.withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS)).thenReturn(stub); return stub; } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java new file mode 100644 index 0000000000..3b699a6ed4 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java @@ -0,0 +1,1034 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +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.netty.shaded.io.netty.handler.ssl.SslProvider; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +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.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Socket-mTLS proof against a synthetic Account handler, not Account issuance or Logging claim + * proof. + */ +class StartSessionOperatorAuthorizationClientMtlsTest { + private static final String NAMESPACE = "logging-test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/logging-test/sa/account-service"; + private static final String LOGGING_URI = + "spiffe://firemud/ns/logging-test/sa/logging-admin-service"; + private static final String STORE_PASSWORD = "synthetic-start-session-authorization-test"; + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ef5b97ec-3cbe-43dc-a85f-f119060386ab"); + private static final UUID CLAIM_OWNER_ID = + UUID.fromString("9bb650bd-38c2-4dc1-8132-1af107358e60"); + private static final String CONTROL_UI_JWT = "synthetic-original-control-ui-jwt-body-only"; + private static final String OPERATOR_REFERENCE = "a".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-11T12:00:00Z"); + private static final Instant EXPIRY = NOW.plusSeconds(240); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + private Server server; + private StartSessionOperatorAuthorizationClient client; + private AtomicInteger rpcCalls; + private IssueHumanOperatorAuthorizationReferenceRequest receivedIssue; + private RecoverOperatorAuthorizationReferenceRequest receivedRecovery; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @BeforeEach + void clearAmbientThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_993L, Long.MAX_VALUE}) + void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence(long reservationFence) + throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("synthetic-issue-recover-01"); + + var issued = + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); + var recovered = + client.recover(tuple, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); + + assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.authorizationReferenceFingerprint()) + .isEqualTo(issued.authorizationReferenceFingerprint()); + assertThat(issued.expiresAt()).isEqualTo(EXPIRY); + assertThat(recovered.expiresAt()).isEqualTo(issued.expiresAt()); + assertThat(recovered.authorityEvidenceBundle()) + .containsExactly(issued.authorityEvidenceBundle()); + assertThat(recovered.bundleReference()).isEqualTo(issued.bundleReference()); + assertThat(issued.postAuthorizationTuple().canonicalBytes()) + .containsExactly(originalTupleBytes(tuple, RESERVATION_OWNER_ID, reservationFence)); + assertThat(recovered.postAuthorizationTuple().canonicalBytes()) + .containsExactly(issued.postAuthorizationTuple().canonicalBytes()); + assertThat(issued.postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID); + assertThat(issued.postAuthorizationTuple().reservationClaimFence()).isEqualTo(reservationFence); + assertThat(recovered.postAuthorizationTuple().reservationClaimFence()) + .isEqualTo(reservationFence); + Map encodedTuple = + JSON.readValue(issued.postAuthorizationTuple().canonicalBytes(), Map.class); + assertThat(encodedTuple.get("reservationClaimFence")) + .isEqualTo(Long.toString(reservationFence)); + assertThat(issued.bundleReference().sourceFence()) + .isNotEqualTo(issued.postAuthorizationTuple().issuanceFence()); + assertThat(issued.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(recovered.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(issued.decodedBundle().controlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat(issued.toString()).doesNotContain(OPERATOR_REFERENCE, CONTROL_UI_JWT); + assertThat(receivedIssue.getControlUiJwt()).isEqualTo(CONTROL_UI_JWT); + assertThat(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(receivedIssue.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(receivedIssue.getReservationClaimFence()).isEqualTo(reservationFence); + assertThat(receivedIssue.getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER_ID.toString()); + assertThat(receivedIssue.getCurrentClaimFence()).isEqualTo(71L); + assertThat(receivedRecovery.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()); + assertThat(receivedRecovery.getReservationOwnerId()) + .isEqualTo(receivedIssue.getReservationOwnerId()); + assertThat(receivedRecovery.getReservationClaimFence()) + .isEqualTo(receivedIssue.getReservationClaimFence()); + assertThat(receivedRecovery.getCurrentClaimOwnerId()) + .isEqualTo(receivedIssue.getCurrentClaimOwnerId()); + assertThat(receivedRecovery.getCurrentClaimFence()) + .isEqualTo(receivedIssue.getCurrentClaimFence()); + assertThat(rpcCalls).hasValue(2); + } + + @Test + void rejectsWrongAccountServerServiceAndNamespaceBeforeSendingRequest() throws Exception { + assertWrongServerIdentity( + pki.identity( + "wrong-service-server", "spiffe://firemud/ns/logging-test/sa/account-other", true)); + assertWrongServerIdentity( + pki.identity( + "wrong-namespace-server", "spiffe://firemud/ns/other-test/sa/account-service", true)); + } + + @Test + void rejectsWrongLoggingCallerServiceAndNamespaceAtSyntheticAccountBoundary() throws Exception { + for (TestIdentity caller : + List.of( + pki.identity( + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false), + pki.identity( + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false))) { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(caller); + client.initialize(); + + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-caller-" + caller.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 8L, + CLAIM_OWNER_ID, + 9L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("PERMISSION_DENIED"); + assertThat(rpcCalls).hasValue(1); + stopServer(); + client.close(); + client = null; + } + } + + @Test + void rejectsUnknownFieldsChangedTupleBindingAndExpirySubstitution() throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + startServer( + pki.accountServer(), + response -> response.toBuilder().setUnknownFields(unknown).build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("different-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + for (UnaryOperator substitute : + List.>of( + response -> response.toBuilder().clearOriginalAccountPostAuthorizationTuple().build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder().setSourceFence("25")) + .build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder() + .setLinearization("18446744073709551614")) + .build())) { + startServer(pki.accountServer(), substitute, UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + } + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(EXPIRY.plusSeconds(1).getEpochSecond())) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void rejectsAuthenticatedLoggingIdentityMismatchAndExpiredEvidence() throws Exception { + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/other-test/sa/logging-admin-service") + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(NOW.minusSeconds(1).getEpochSecond())) + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("expired-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void deniesIssueAndRecoveryBeforeNetworkUnderSqlOrSynchronization() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("pre-network-denial-01"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + assertThat(rpcCalls).hasValue(0); + } + + @Test + void syntheticMutualTlsRejectsMissingClientCertificateWithSharedTlsAssertion() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + SSLContext trustOnlyContext = SSLContext.getInstance("TLS"); + var trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry("trusted-test-ca", pki.caCertificate()); + var trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + trustOnlyContext.init(null, trustManagers.getTrustManagers(), new SecureRandom()); + + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = + (SSLSocket) + trustOnlyContext + .getSocketFactory() + .createSocket("127.0.0.1", server.getPort())) { + socket.setSoTimeout(2_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + + assertThat(failure).isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); + assertThat(rpcCalls).hasValue(0); + } + + private void assertWrongServerIdentity(TestIdentity serverIdentity) throws Exception { + startServer(serverIdentity, UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-server-" + serverIdentity.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 10L, + CLAIM_OWNER_ID, + 11L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + assertThat(rpcCalls).hasValue(0); + stopTransportOnly(); + } + + private void assertInvalidResponse() { + assertThatThrownBy( + () -> + client.issueHuman( + tuple("invalid-account-result-01"), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 12L, + CLAIM_OWNER_ID, + 13L)) + .isInstanceOf(IllegalStateException.class); + assertThat(rpcCalls).hasValue(1); + } + + private void startServer( + TestIdentity serverIdentity, + UnaryOperator issueMutation, + UnaryOperator recoverMutation) + throws Exception { + rpcCalls = new AtomicInteger(); + receivedIssue = null; + receivedRecovery = null; + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void issueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedIssue = request.toBuilder().build(); + try { + observer.onNext(issueMutation.apply(issueResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + @Override + public void recoverOperatorAuthorizationReference( + RecoverOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedRecovery = request.toBuilder().build(); + try { + observer.onNext(recoverMutation.apply(recoveryResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + }; + ServerInterceptor requestMetadataGuard = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (headers.get(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER)) + != null) { + call.close(Status.PERMISSION_DENIED, new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate()), + SslProvider.JDK) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build()) + .addService( + ServerInterceptors.intercept( + service, requestMetadataGuard, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private void stopTransportOnly() throws Exception { + if (client != null) { + client.close(); + client = null; + } + stopServer(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private StartSessionOperatorAuthorizationClient newClient(TestIdentity clientIdentity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.getPort()); + return new StartSessionOperatorAuthorizationClient( + endpoints, + pki.clientProperties(clientIdentity), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, java.time.ZoneOffset.UTC)); + } + + private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( + IssueHumanOperatorAuthorizationReferenceRequest request) { + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse recoveryResponse( + RecoverOperatorAuthorizationReferenceRequest request) { + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) + .build(); + } + + private static byte[] originalTupleBytes( + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long fence) { + var reference = bundleReference(); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + LOGGING_URI, + FINGERPRINT, + reservationOwner, + fence, + bundleFor(tuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.getBundleVersion(), + reference.getSourceVersion(), + reference.getSourceFence(), + reference.getLinearization())) + .canonicalBytes(); + } + + private static byte[] bundleFor( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = tuple.action().scope().tenantId().toString(); + Map root = + new LinkedHashMap<>( + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", tuple.actor().accountId().toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + EXPIRY.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", tuple.actor().accountId().toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"))); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } catch (IOException fixtureFailure) { + throw new IllegalStateException( + "Synthetic Account authority bundle fixture could not be encoded", fixtureFailure); + } + } + + private static AuthorityEvidenceBundleReference bundleReference() { + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) + .setSourceVersion("17") + .setSourceFence("24") + .setLinearization("18446744073709551615") + .build(); + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic Account authorization client transport proof"); + var shared = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(requestId, ACTOR_ID, action); + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(shared.canonicalJson()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(IssueHumanOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(RecoverOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private record TestIdentity( + String alias, + String workloadUri, + boolean server, + Path store, + Path certificatePem, + Path privateKeyPem, + PrivateKey privateKey, + X509Certificate certificate) {} + + private static final class TestPki { + private final Path directory; + private final Path caStore; + private final Path caCertificatePem; + private final X509Certificate caCertificate; + private final Map identities; + + private TestPki( + Path directory, + Path caStore, + Path caCertificatePem, + X509Certificate caCertificate, + Map identities) { + this.directory = directory; + this.caStore = caStore; + this.caCertificatePem = caCertificatePem; + this.caCertificate = caCertificate; + this.identities = identities; + } + + private static TestPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("start-session-authorization-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD StartSession authorization synthetic test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caCertificate = directory.resolve("start-session-authorization-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-rfc"); + var identities = new LinkedHashMap(); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "account-server", ACCOUNT_URI, true)); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "logging-client", LOGGING_URI, false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-server", + "spiffe://firemud/ns/logging-test/sa/account-other", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-server", + "spiffe://firemud/ns/other-test/sa/account-service", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false)); + return new TestPki( + directory, caStore, caCertificate, readCertificate(caCertificate), identities); + } + + private static void addIdentity(Map identities, TestIdentity identity) { + identities.put(identity.alias(), identity); + } + + private TestIdentity accountServer() { + return identities.get("account-server"); + } + + private TestIdentity loggingClient() { + return identities.get("logging-client"); + } + + private TestIdentity identity(String alias, String workloadUri, boolean server) { + TestIdentity identity = identities.get(alias); + if (identity == null + || !identity.workloadUri().equals(workloadUri) + || identity.server() != server) { + throw new IllegalArgumentException("Unexpected synthetic mTLS identity fixture"); + } + return identity; + } + + private X509Certificate caCertificate() { + return caCertificate; + } + + private CommonGrpcClientProperties clientProperties(TestIdentity identity) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(identity.certificatePem().toString()); + properties.setPrivateKey(identity.privateKeyPem().toString()); + properties.setCaCert(caCertificatePem.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String workloadUri, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate leaf = (X509Certificate) keyStore.getCertificate(alias); + Path certificatePem = + writePem(directory.resolve(alias + "-leaf.pem"), "CERTIFICATE", leaf.getEncoded()); + Path privateKeyPem = + writePem( + directory.resolve(alias + "-private.pem"), "PRIVATE KEY", privateKey.getEncoded()); + return new TestIdentity( + alias, workloadUri, server, store, certificatePem, privateKeyPem, privateKey, leaf); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-start-session-auth-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("synthetic workload keytool fixture timed out"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("synthetic workload keytool fixture failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index d84515884e..b552f2f8f1 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -50,6 +50,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; class StartSessionOperatorAuthorizationClientTest { @@ -435,6 +436,71 @@ void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throw } } + @Test + void deniesIssueAndRecoverBeforeAccountUnderSqlOrSynchronization() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-no-ambient-transaction"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsExpiredRecoveryWithoutReplacementIssuance() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-expired-recovery"); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + Instant expired = NOW.minusSeconds(1); + RecoverOperatorAuthorizationReferenceResponse response = + recoverResponse(tuple, expired, bundleBytes(tuple, NOW.minusSeconds(2), expired)); + when(stub.recoverOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("expired"); + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsAccountReferenceLifetimeAboveItsConfiguredMaximum() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-overlong-reference"); + assertRejected( + tuple, + issueResponse(tuple, NOW.plusSeconds(301), bundleBytes(tuple, NOW.plusSeconds(301)))); + } + private void assertRejected( StartSessionPreAuthorizationReservationTuple tuple, IssueHumanOperatorAuthorizationReferenceResponse response) @@ -557,6 +623,12 @@ private static AuthorityEvidenceBundleReference reference() { private static byte[] bundleBytes( StartSessionPreAuthorizationReservationTuple tuple, Instant expiry) throws Exception { + return bundleBytes(tuple, NOW, expiry); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant evaluatedAt, Instant expiry) + throws Exception { String tenantId = TENANT_ID.toString(); Map projection = Map.of( @@ -569,7 +641,7 @@ private static byte[] bundleBytes( "projectionStatus", "CURRENT", "evaluatedAt", - NOW.toString(), + evaluatedAt.toString(), "expiresAt", expiry.toString()); Map authority = diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index 6409516c44..fe9a6f0b38 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -14,7 +14,6 @@ import static org.mockito.Mockito.when; import io.grpc.Status; -import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -22,8 +21,10 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.security.SessionContext; @@ -45,10 +46,11 @@ import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import tools.jackson.databind.json.JsonMapper; +import org.springframework.transaction.support.TransactionSynchronizationManager; class StartSessionAuthorizationCoordinatorTest { private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); @@ -65,12 +67,11 @@ class StartSessionAuthorizationCoordinatorTest { UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); private static final long NOW_MILLIS = NOW.toEpochMilli(); - private static final String CONTROL_UI_TOKEN = "operator-control-ui-secret"; + private static final String CONTROL_UI_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0In0.c2ln"; private static final String OPAQUE_REFERENCE = "r".repeat(43); private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); private static final String LOGGING_IDENTITY = "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; - private static final JsonMapper JSON = JsonMapper.builder().build(); private final StartSessionPreAuthorizationReservationRepository repository = mock(StartSessionPreAuthorizationReservationRepository.class); @@ -79,12 +80,25 @@ class StartSessionAuthorizationCoordinatorTest { repository, Clock.fixed(NOW, ZoneOffset.UTC)); private final StartSessionOperatorAuthorizationClient accountClient = mock(StartSessionOperatorAuthorizationClient.class); + private final AtomicReference exactReadback = new AtomicReference<>(); private final StartSessionAuthorizationCoordinator coordinator = - new StartSessionAuthorizationCoordinator(reservations, accountClient); + new StartSessionAuthorizationCoordinator("world-runtime", reservations, accountClient); + + @BeforeEach + void setAuthenticatedTenantAdminContext() { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + } @AfterEach void clearAuthenticatedContext() { SessionContext.clear(); + TransactionSynchronizationManager.clear(); } @Test @@ -134,10 +148,15 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .isEqualTo(LOGGING_IDENTITY); assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); assertThat(duplicate.handoff()).isNull(); + assertThat(duplicate.authorizedReadback()).isPresent(); assertThat(first.toString()) .doesNotContain(CONTROL_UI_TOKEN) .doesNotContain(OPAQUE_REFERENCE) .doesNotContain(FINGERPRINT); + assertThat(duplicate.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); assertThat(first.handoff().toString()) .doesNotContain(CONTROL_UI_TOKEN) .doesNotContain(OPAQUE_REFERENCE) @@ -148,6 +167,19 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); ArgumentCaptor handoffId = ArgumentCaptor.forClass(UUID.class); InOrder persistenceOrder = inOrder(accountClient, repository); + persistenceOrder + .verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + persistenceOrder + .verify(repository) + .markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS)); persistenceOrder .verify(accountClient) .issueHuman( @@ -158,6 +190,14 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere currentOwner.capture(), eq(1L)); assertThat(originalOwner.getValue()).isEqualTo(currentOwner.getValue()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L)); verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); persistenceOrder .verify(repository) @@ -176,6 +216,12 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .doesNotContain(CONTROL_UI_TOKEN); assertThat(persistedTuple.getValue()) .isEqualTo(first.handoff().postAuthorizationTuple().canonicalJson()); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode( + persistedTuple.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .canonicalBytes()) + .containsExactly(first.handoff().postAuthorizationTuple().canonicalBytes()); + persistenceOrder.verify(repository).findAuthorizedExact(eq(tuple)); persistenceOrder .verify(repository) .beginOwnerExecution( @@ -191,6 +237,299 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere assertThat(handoffId.getValue()).isEqualTo(first.handoff().ownerExecutionHandoff().handoffId()); } + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeReservationWork() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-ambient-sql"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> coordinator.recover(tuple)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(repository, accountClient); + } + + @Test + void nullReferenceAndWrongWorkloadCannotCompleteOrHandoff() throws Exception { + for (String caseName : List.of("null-reference", "wrong-workload")) { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-" + caseName); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenAnswer( + invocation -> { + AuthorizationReference response = + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue()); + if (caseName.equals("null-reference")) { + when(response.operatorAuthorizationReference()).thenReturn(null); + } else { + when(response.authenticatedLoggingWorkloadIdentity()) + .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); + } + return response; + }); + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .completeAuthorization( + eq(tuple), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + eq(tuple), + anyString(), + any(), + anyLong(), + any(), + anyLong(), + anyString(), + any(), + anyLong()); + } + } + + @Test + void recoveryFailureKeepsOriginalPendingClaimAndDoesNotIssueReplacement() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery-unavailable"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + Result result = coordinator.recover(tuple); + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RECOVERY_OUTCOME_UNKNOWN); + assertThat(result.snapshot()).isEqualTo(pending); + assertThat(result.handoff()).isNull(); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + } + + @Test + void namespaceJwtAndHumanTenantAdminGuardsRunBeforeStorage() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-input-guards"); + StartSessionOperatorAction action = tuple.action(); + StartSessionOperatorAction wrongNamespaceAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + new StartSessionOperatorAction.Scope(TENANT_ID, "other-runtime"), + action.target(), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), wrongNamespaceAction, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> coordinator.begin(tuple.controlPlaneRequestId(), action, "not-a-jwt")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN + ".extra")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> coordinator.begin(tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin authority"); + + verifyNoInteractions(repository, accountClient); + } + + @Test + void beginAcceptsCanonicalCompactThreeSegmentJwtEnvelope() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-valid-jwt-envelope"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = + coordinator.begin(tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN); + + assertThat(CONTROL_UI_TOKEN.split("\\.", -1)).hasSize(3); + assertThat(result.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + } + + @Test + void changedTupleForExistingRequestConflictsWithoutAccountCall() { + StartSessionPreAuthorizationReservationTuple requested = tuple("coordinator-tuple-conflict"); + StartSessionOperatorAction action = requested.action(); + StartSessionOperatorAction changedAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + action.scope(), + new StartSessionOperatorAction.Target(92L, action.target().ownerAccountId()), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + StartSessionPreAuthorizationReservationTuple conflicting = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + requested.controlPlaneRequestId(), changedAction); + Snapshot existing = snapshot(conflicting, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire( + eq(requested), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(existing, false)); + + assertThatThrownBy(() -> coordinator.issueHuman(requested, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(repository, never()) + .markAuthorizationPending( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyLong()); + } + + @Test + void productionReservationMutationRemainsDeniedByDefault() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-default-denial"); + StartSessionPreAuthorizationReservationService productionDefault = + new StartSessionPreAuthorizationReservationService(repository); + + assertThatThrownBy(() -> productionDefault.acquire(tuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("disabled for production construction"); + + verifyNoInteractions(repository); + } + + @Test + void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHandoff() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-missing"); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + @Test + void conflictingIndependentAuthorizedReadbackCannotAdvanceOwnerPending() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-conflict"); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer( + invocation -> { + AuthorizedSnapshot exact = exactReadback.get(); + Snapshot snapshot = exact.reservationSnapshot(); + Snapshot substituted = + new Snapshot( + snapshot.tuple(), + snapshot.mutationDigest(), + snapshot.phase(), + snapshot.state(), + snapshot.reservationClaimFence(), + snapshot.claimFence(), + snapshot.claimExpiresAtEpochMillis() + 1L, + snapshot.claimState(), + snapshot.claimPurpose()); + return Optional.of( + new AuthorizedSnapshot( + substituted, + exact.postAuthorizationTuple(), + exact.reservationOwnerId(), + exact.currentClaimOwnerId(), + exact.handoff())); + }); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + @Test void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery"); @@ -203,7 +542,12 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result result = coordinator.recover(tuple); @@ -341,7 +685,12 @@ void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Except pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -391,6 +740,7 @@ void nonWinningAndUnavailableAuthorizationPathsNeverDispatchOwner() { eq(duplicateTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(duplicateTuple))).thenReturn(Optional.empty()); StartSessionPreAuthorizationReservationTuple unavailableTuple = tuple("coordinator-dispatch-unavailable"); when(repository.acquireRecoveryClaim( @@ -504,7 +854,9 @@ void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exceptio .thenAnswer( invocation -> authorizationReference( - tuple, invocation.getArgument(2), invocation.getArgument(3))); + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.beginOwnerExecution( eq(tuple), @@ -520,9 +872,14 @@ void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exceptio new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( tuple.controlPlaneRequestId())); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf( - StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason + .OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN); + assertThat(result.handoff()).isNull(); verify(repository) .completeAuthorization( eq(tuple), @@ -553,7 +910,8 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) .thenReturn( - new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); when(repository.markAuthorizationPending( eq(tuple), eq(tuple.mutationDigest()), @@ -567,9 +925,17 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + Result duplicate = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat(first.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(first.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + assertThat(first.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); verify(repository, never()) .completeAuthorization( @@ -578,6 +944,9 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { .beginOwnerExecution( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong()); } @Test @@ -594,8 +963,11 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr (UUID) invocation.getArgument(2), ((Number) invocation.getArgument(3)).longValue())); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf(IllegalArgumentException.class); + Result invalidAccountResult = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(invalidAccountResult.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(invalidAccountResult.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); verify(repository, never()) .completeAuthorization( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); @@ -631,14 +1003,79 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( staleTuple.controlPlaneRequestId())); - assertThatThrownBy(() -> coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN)) - .isInstanceOf( - StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + Result staleCompletion = coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN); + assertThat(staleCompletion.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(staleCompletion.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); verify(repository, never()) .beginOwnerExecution( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); } + @Test + void sourceFenceAndLinearizationMismatchesNeverReachLoggingCompletion() throws Exception { + List alteredTupleReferences = + List.of( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "25", + "18446744073709551615"), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "24", + "18446744073709551614")); + int caseNumber = 0; + for (var alteredReference : alteredTupleReferences) { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("coordinator-capture-reference-mismatch-" + caseNumber++); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue(), + alteredReference)); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + verify(repository, never()) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS)); + verify(repository, never()) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + } + private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple tuple) { Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); @@ -661,6 +1098,7 @@ private void stubAuthorizationEnrichment( StartSessionPreAuthorizationReservationTuple tuple, boolean transitioned, boolean mayDispatch) { + exactReadback.set(null); when(repository.completeAuthorization( eq(tuple), eq(tuple.mutationDigest()), @@ -693,12 +1131,15 @@ private void stubAuthorizationEnrichment( currentOwner.equals(reservationOwner) && currentFence == reservationFence ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); - return new StartSessionPreAuthorizationReservationRepository - .AuthorizationTransitionResult( + AuthorizedSnapshot authorizedSnapshot = new AuthorizedSnapshot( - authorized, postTuple, reservationOwner, currentOwner, null), - transitioned); + authorized, postTuple, reservationOwner, currentOwner, null); + exactReadback.set(authorizedSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult(authorizedSnapshot, transitioned); }); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer(invocation -> Optional.ofNullable(exactReadback.get())); when(repository.beginOwnerExecution( eq(tuple), eq(tuple.mutationDigest()), @@ -733,26 +1174,39 @@ private void stubAuthorizationEnrichment( currentOwner.equals(reservationOwner) && currentFence == reservationFence ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); - return new StartSessionPreAuthorizationReservationRepository - .OwnerExecutionTransitionResult( + AuthorizedSnapshot ownerPendingSnapshot = new AuthorizedSnapshot( ownerPending, postTuple, reservationOwner, currentOwner, - new OwnerExecutionHandoff(handoffId)), - mayDispatch); + new OwnerExecutionHandoff(handoffId)); + exactReadback.set(ownerPendingSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult(ownerPendingSnapshot, mayDispatch); }); } private static AuthorizationReference authorizationReference( - StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long claimFence) + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence) + throws Exception { + return authorizationReference(tuple, reservationOwner, reservationFence, bundleReference()); + } + + private static AuthorizationReference authorizationReference( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence, + StartSessionAuthorityEvidenceBundle.BundleReference tupleReference) throws Exception { AuthorizationReference response = mock(AuthorizationReference.class); when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); when(response.expiresAt()).thenReturn(NOW.plusSeconds(300)); - when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(response.authorityEvidenceBundle()).thenReturn(bundle); when(response.bundleReference()).thenReturn(bundleReference()); when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); when(response.postAuthorizationTuple()) @@ -762,9 +1216,9 @@ private static AuthorizationReference authorizationReference( LOGGING_IDENTITY, FINGERPRINT, reservationOwner, - claimFence, - bundleBytes(tuple, NOW.plusSeconds(300)), - bundleReference())); + reservationFence, + bundle, + tupleReference)); return response; } @@ -783,82 +1237,30 @@ private static StartSessionOwnerHandoffResult ownerEcho( } private static byte[] bundleBytes( - StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) throws IOException { - String tenantId = TENANT_ID.toString(); - Map projection = - Map.of( - "sourceType", - "ACCOUNT", - "sourceEvidenceId", + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + shared(tuple), + new Values( + ISSUANCE_ID, "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", - NOW.toString(), - "expiresAt", - expiresAt.toString()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map evidence = - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - ACTOR_ID.toString(), - "controlUiTokenJti", - TOKEN_JTI.toString(), - "role", - "tenantAdmin", - "accountGeneration", + NOW, + expiresAt, + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + TOKEN_JTI, "2", - "tenantGeneration", - "3"); - Map bundle = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR_ID.toString(), - "applicableTenantId", tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", ISSUANCE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - evidence); - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + "3")); } private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { return new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "18446744073709551615"); } private static Snapshot snapshot( From 7369cb22619b00b16ddd34491b4659f81c2f255e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 05:24:12 +1300 Subject: [PATCH 2/9] Record qualified Entity parent carry and preserve receiver proof attribution --- .../game-authoring-publishing-and-activation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 03a8231a3f..5c486f193c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. ### Coherent owner receiving prerequisite @@ -14,7 +14,7 @@ The receiver implements mandatory fresh-v2 operation values, actual ordinary ass The complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passes formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executes 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executes all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history has 62 entries; upgrade and fresh histories have 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases keep their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verifies their unchanged inputs as up-to-date rather than relabeling them fresh. -Final parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changes only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`; all Account, Common, Game Design, Logging and migration inputs are byte-identical. The parent proofs separately cover Entity's 237 unit and 26 physical PostgreSQL cases and Account's 18 physical PostgreSQL cases without failures, errors or skips. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. +Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Final parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs remain byte-identical. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passes freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. External Account/World inputs in the storage and source fixtures remain explicitly controlled. Current Java callers issue complete fresh-v2 operations; the decoder preserves original three-frame v1 bytes as read-only history without inventory authority. Installing source tables and proving owner-local behavior does not register a genuine producer, establish rebuilt runtime proof for the receiver, authorize activation or complete any Gameplay handoff. All four genuine handoffs, full publication, protected activation, Entity placement and operational-region delivery remain open; broader Unit 1B stays paused. The owning storage and reviewed-base contract is [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). From bb2abcdfcab301cb2622c9042f13e487ceb6c3d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 05:52:14 +1300 Subject: [PATCH 3/9] Record disjoint controller parent carry and preserved owner proof --- .../game-authoring-publishing-and-activation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 5c486f193c..b68c6b9f50 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `d7c8f84fa947644a651304205803c3919c81684e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. ### Coherent owner receiving prerequisite @@ -14,7 +14,7 @@ The receiver implements mandatory fresh-v2 operation values, actual ordinary ass The complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passes formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executes 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executes all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history has 62 entries; upgrade and fresh histories have 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases keep their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verifies their unchanged inputs as up-to-date rather than relabeling them fresh. -Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Final parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs remain byte-identical. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passes freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. +Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs remain byte-identical. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passes freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. Current parent `d7c8f84fa947644a651304205803c3919c81684e` changes only the review controller and its tests from `4925747`; all owner runtime and migration inputs remain byte-identical. The receiver carries those proofs with their original attribution, while exact-head CI and review remain separate. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. External Account/World inputs in the storage and source fixtures remain explicitly controlled. Current Java callers issue complete fresh-v2 operations; the decoder preserves original three-frame v1 bytes as read-only history without inventory authority. Installing source tables and proving owner-local behavior does not register a genuine producer, establish rebuilt runtime proof for the receiver, authorize activation or complete any Gameplay handoff. All four genuine handoffs, full publication, protected activation, Entity placement and operational-region delivery remain open; broader Unit 1B stays paused. The owning storage and reviewed-base contract is [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). From 24b64275a756d9375d1e61ef7e53a353160a09a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:28:33 +1300 Subject: [PATCH 4/9] Fix receiver reference timing and transaction witness projection --- .../logging-admin-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 6 ++ ...ame-authoring-publishing-and-activation.md | 6 +- ..._config_transaction_witness_projection.sql | 12 ++++ ...StorageUpgradePostgresIntegrationTest.java | 71 +++++++++++++++++-- ...artSessionOperatorAuthorizationClient.java | 6 +- ...essionOperatorAuthorizationClientTest.java | 35 +++++++-- 7 files changed, 120 insertions(+), 18 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 0e48888d45..741cdcec8e 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -14,6 +14,8 @@ When enabled, the Spring composition requires the configured canonical workload Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple with its exact reserved operation and validated response, persists those unchanged Account bytes, and independently reads back the same durable authorization before advancing the one-time owner handoff. Exact retries may observe secret-free durable state but never return another transient reference or dispatch again. Ambiguous Account calls, local completion, readback, or owner-pending transitions remain pending with no automatic replacement issuance or rearming. ISSUE, RECOVER, and owner forwarding require no ambient SQL transaction or synchronization. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns original tuple and capture-reference binding; this local receiving boundary does not activate operator ingress or replace Account current-authority and expiry decisions. +The receiving client requires the returned expiry to be strictly later than its local clock and exactly equal to the authenticated Account bundle's expiry. Account enforces reference lifetime against its own issuance timestamp; Logging does not infer that lifetime from a different host's current clock or add a numerical skew allowance. Account projection evaluation time remains source-capture evidence rather than an issuance timestamp. + ## Account Audit Ingress and Receipt The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 4d5c8ed790..75ccedb7cf 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -252,3 +252,9 @@ Entry format: - Observation: the complete preserved delta had 84 paths, with a coherent 63-path Game Design boundary after inherited Account/process and separate Logging paths were accounted for. Current-owner proof required actual asset genesis, reviewed evidence and synchronized projection; decoding retained v1 history could not substitute for those callers. PostgreSQL's unnamed constraint identity also differed from jOOQ's H2 metadata emulation. - Expected pattern: inventory committed, modified tracked and untracked postimages together, then reconcile actual imports and owner invariants on the selected parent. Keep retained-byte proof separate from current positive owner proof. Use targeted jOOQ ignore markers only for procedural or constraint blocks that do not change generated columns, with independent PostgreSQL upgrade and current-owner proof. - Current status: the complete 63-path Game Design receiver on the preparation parent passes its canonical gate, including all 127 physical PostgreSQL cases without skips. This does not establish genuine cross-service producer authority or packaged runtime proof. + +- `2026-10-14`: Fresh database proof needs a new run identity + - Context: a supplementary Gameplay fresh-bootstrap proof reused a previously completed run identity after canonical teardown. + - Observation: the run retained immutable authored-world source receipts while its PostgreSQL volume was rebuilt, so Game Design correctly rejected the new database owner evidence as conflicting with the old receipt. Reusing the ownership capability did not make the two database histories one proof. + - Expected pattern: allocate a new run ID and ownership token for a new fresh-database proof; preserve the prior receipt and use canonical run-owned teardown. Use the restart entrypoint when proving continuity of an existing deployment. Do not delete receipt evidence to make a reused fresh-bootstrap identity succeed or credit a setup failure as runtime proof. + - Current status: the reused-identity invocation failed and was canonically torn down; a unique-identity invocation rebuilt current jars and images, passed both WebSocket and Telnet player-flow baselines, and completed canonical teardown. 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 b68c6b9f50..0991926104 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,11 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `d7c8f84fa947644a651304205803c3919c81684e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 63 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one dated process observation. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `d7c8f84fa947644a651304205803c3919c81684e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 64 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. ### Coherent owner receiving prerequisite -The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. +The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. + +After the first CLI review's two accepted corrections, the consolidated Game Design and Logging full-service gate passes in 4 minutes 24 seconds with formatting, actual Game Design jOOQ generation, static analysis and documentation checks. Game Design freshly executes 502 unit cases and all 128 physical PostgreSQL cases with zero failures, errors or skips. The nine-case storage-upgrade suite includes typed transaction-ID projection across a synthetic epoch boundary, an actual enabled template-insert witness and rejection of a forged witness; it does not advance the PostgreSQL cluster through four billion transactions. Fresh and upgraded combined histories now contain 85 entries through V1025, with retained predecessor checksums and rows preserved. Logging's 272 unit and 25 PostgreSQL/service integration cases executed in the preceding gate on unchanged Logging inputs and remain up-to-date in the successful consolidated rerun. Issue and recovery accept an exact Account reference under a different issuer clock while retaining strict local expiry and complete response binding; Account's own issuance-lifetime enforcement remains unchanged. These owner and receiving proofs do not establish genuine production authority or rebuilt receiver activation. The complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passes formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executes 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executes all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history has 62 entries; upgrade and fresh histories have 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases keep their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verifies their unchanged inputs as up-to-date rather than relabeling them fresh. diff --git a/services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql b/services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql new file mode 100644 index 0000000000..d1d08db99d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql @@ -0,0 +1,12 @@ +-- PostgreSQL executes this guard; the native upgrade proof verifies it. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_template_config_insert_witness() RETURNS TRIGGER AS $$ +BEGIN + IF pg_trigger_depth() <> 2 OR NEW.creation_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_templates t WHERE t.id = NEW.template_id + AND t.xmin = pg_current_xact_id()::xid) THEN + RAISE EXCEPTION 'template insert witness requires actual row insert trigger' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index dc483b0092..371decc5d4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -154,12 +154,12 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua dsl.fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(84L); + .isEqualTo(85L); assertThat( dsl.fetchSingle( "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") .get(0, Integer.class)) - .isEqualTo(1024); + .isEqualTo(1025); assertEnabledGuards(dsl, schema); } @@ -206,7 +206,7 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageT .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(84L); + .isEqualTo(85L); assertThat(retainedRows(fixture)).isEqualTo(rows); assertEnabledGuards(fixture); } @@ -235,7 +235,7 @@ void fullStorageUpgradeRetainsParentV1RowsBytesChecksumsAndOwnerReads() throws E .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(84L); + .isEqualTo(85L); assertThat(retainedRows(fixture)).isEqualTo(rows); assertThat(GameDesignPublicationOperation.fromStored(original).canonicalBytes()) .containsExactly(original); @@ -334,14 +334,14 @@ void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() .fetchSingle( "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") .get(0, Integer.class)) - .isEqualTo(1024); + .isEqualTo(1025); assertThat( fixture .dsl() .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(84L); + .isEqualTo(85L); assertThat(predecessorChecksums(fixture)).isEqualTo(parentChecksums); assertThat(reviewedBaseRow(fixture, binding)).isEqualTo(beforeRow); var retained = new GameDesignReviewedBaseRepository(fixture.dsl()).read(binding).orElseThrow(); @@ -457,6 +457,65 @@ void retainedTerminalFailureRemainsReadableWithItsOriginalReceiptAfterUpgrade() assertEnabledGuards(fixture); } + @Test + void upgradedTemplateInsertWitnessUsesEpochSafeXidProjectionAndRejectsForgery() throws Exception { + var fixture = fixture(false); + upgrade(fixture); + assertEnabledGuards(fixture); + + assertThat( + fixture + .dsl() + .fetchSingle("SELECT ('4294967297'::xid8)::xid::TEXT") + .get(0, String.class)) + .isEqualTo("1"); + assertThatThrownBy(() -> fixture.dsl().fetchSingle("SELECT ('4294967297'::TEXT::XID)::TEXT")) + .satisfies( + failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("22003"); + }); + + Long templateId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, ?, '{}'::JSONB) RETURNING id", + fixture.operation().tenantKey(), + "witness-" + UUID.randomUUID()) + .get(0, Long.class); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_row_insert WHERE template_id = ? AND creation_transaction_id ~ '^[1-9][0-9]*$'", + templateId) + .get(0, Long.class)) + .isEqualTo(1L); + + deny( + fixture, + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_template_config_source_row_insert (template_id, creation_transaction_id) VALUES (?, pg_current_xact_id()::TEXT)", + templateId), + "template insert witness requires actual row insert trigger"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_row_insert WHERE template_id = ?", + templateId) + .get(0, Long.class)) + .isEqualTo(1L); + assertEnabledGuards(fixture); + } + @Test void newParentV1ReservationIsDeniedAndRawV2ReservationUsesActualOwnerSelectionAndAttempt() throws Exception { diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java index 66aa5e8e7a..c655a41f5f 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -6,7 +6,6 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; -import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -49,7 +48,6 @@ public class StartSessionOperatorAuthorizationClient StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 2_048; - private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; private static final int MAX_REFERENCE_BYTES = 128; private static final long RPC_DEADLINE_SECONDS = 5L; @@ -282,12 +280,10 @@ private AuthorizationReference validateResponse( } Instant expiresAt = exactExpiry(expiryTimestamp); Instant now = clock.instant(); + // Account bounds issuance lifetime on its own clock; local time only checks expiry. if (!expiresAt.isAfter(now)) { throw new IllegalStateException("Account authorization response is expired"); } - if (expiresAt.isAfter(now.plus(MAX_REFERENCE_LIFETIME))) { - throw malformedResponse(); - } StartSessionAuthorityEvidenceBundle bundle = StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundle); bundle.requireTupleBinding(tuple); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index b552f2f8f1..893486931a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -326,6 +326,7 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception valid.getBundleReference().toBuilder().setUnknownFields(unknownFields()).build()) .build()); assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.plusSeconds(301))).build()); + assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW)).build()); assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.minusSeconds(1))).build()); RecoverOperatorAuthorizationReferenceResponse validRecovery = @@ -494,11 +495,35 @@ void rejectsExpiredRecoveryWithoutReplacementIssuance() throws Exception { } @Test - void rejectsAccountReferenceLifetimeAboveItsConfiguredMaximum() throws Exception { - StartSessionPreAuthorizationReservationTuple tuple = tuple("client-overlong-reference"); - assertRejected( - tuple, - issueResponse(tuple, NOW.plusSeconds(301), bundleBytes(tuple, NOW.plusSeconds(301)))); + void issueAndRecoverAcceptAccountLifetimeUnderLocalClockSkew() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-account-clock-ahead"); + Instant accountEvaluatedAt = NOW.plusSeconds(120); + Instant accountExpiry = accountEvaluatedAt.plusSeconds(300); + byte[] bundle = bundleBytes(tuple, accountEvaluatedAt, accountExpiry); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenReturn(issueResponse(tuple, accountExpiry, bundle)); + when(stub.recoverOperatorAuthorizationReference(any())) + .thenReturn(recoverResponse(tuple, accountExpiry, bundle)); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + StartSessionOperatorAuthorizationClient.AuthorizationReference issued = + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + StartSessionOperatorAuthorizationClient.AuthorizationReference recovered = + client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 12L); + + assertThat(accountExpiry).isAfter(NOW.plusSeconds(300)); + assertThat(issued.expiresAt()).isEqualTo(accountExpiry); + assertThat(recovered.expiresAt()).isEqualTo(accountExpiry); + assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(recovered.authorityEvidenceBundle()).containsExactly(bundle); + verify(stub).issueHumanOperatorAuthorizationReference(any()); + verify(stub).recoverOperatorAuthorizationReference(any()); + } } private void assertRejected( From 371f0dcedc75690aadb7cb267b4a19ddbc8c16ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:14:05 +1300 Subject: [PATCH 5/9] Bind reviewed schemas and exact Draft epochs with focused proof --- .../game-design-service/asset-storage.md | 18 +-- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 12 +- .../DraftSynchronizedVisibilityEvidence.java | 6 +- ...aftSynchronizedVisibilityEvidenceTest.java | 134 ++++++++++++++++++ ...DesignPublicationOperationBindingTest.java | 10 +- .../GameDesignReviewedBaseRepository.java | 3 + .../GameDesignSourceRepository.java | 2 +- ...StorageUpgradePostgresIntegrationTest.java | 34 ++++- .../GameDesignReviewedBaseEvidenceTest.java | 58 +++++++- 10 files changed, 253 insertions(+), 30 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index c8854e4422..02cc4453a6 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,7 +6,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without frozen snapshot references may still be updated. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method fails closed because it carries no reviewed commit authority; the ordinary source-owner path and synchronized projection have controlled-input local PostgreSQL proof, while registered production authoring remains unavailable; exports use only the version's mapped set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without frozen snapshot references may still be updated. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. `version_asset` rows are written only by `ordinary_asset_snapshot_projection` from synchronized ordinary asset snapshots; the direct `associateDraftAsset` method fails closed. The ordinary source-owner path and synchronized projection have controlled-input local PostgreSQL proof, while production authoring ingress remains unavailable; exports use only the exact projected set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. - **Current upload admission gap:** `GameAssetServiceImpl` now returns a structured owner-proof refusal before accessing `MultipartFile` or the repository because Account commit-bound authority is not wired. This deny-only containment does not implement the Account gate or make the Gateway-exposed route readiness-approved; it does not delete or rewrite previously accepted `game_assets` rows. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. - **Hosted-content gate gap:** Current publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route forwards `/api/design/assets` (after `StripPrefix=2`) to `POST /assets`, where the service refuses before file access or persistence. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable per-version source snapshot and export candidate preserve the selected rows and exact content-addressed object-key/digest evidence; the object writer verifies exact readback. Published repair independently reads the candidate and matches its manifest, artifact digests, and object keys to the release attestation before any object write. This does not implement the target global publication/purge fence or private candidate isolation; source identity and payload fields are database-protected while frozen snapshots reference them, and physical object-store proof remains unavailable. @@ -31,7 +31,7 @@ Logical world and entity templates (regions, rooms, items, NPCs, loot tables, sc A fresh full-Draft insertion establishes ordinary asset genesis in the same owner transaction as policy and command genesis, bound to the original Version insertion witness. Typed `ASSET_REFERENCE` revisions use the existing reviewed commit and coordinator application slot. Each declared source family contributes its exact application result and affected epoch to one complete Game Design owner outcome. Only the synchronized commit fence permits a source snapshot and its `version_asset` projection; direct mapping association is not an authority path. -A new export snapshot requires the exact synchronized ordinary source snapshot, including an explicitly owner-founded empty set. Its items bind the source row, usage key, content type, byte size and actual-byte digest. Already retained V37 export snapshots remain read-only with their original bytes and metadata; absence of source history cannot be interpreted as empty or backfilled. The fresh reviewed-base and retained-evidence boundary is owned by [Version Control](version-control.md#selected-publication-storage-and-retained-operations). +A new export snapshot requires the exact synchronized ordinary source snapshot, including an explicitly owner-founded empty set. A Version without asset genesis cannot freeze an export snapshot; absence of source history cannot be interpreted as empty or backfilled. Its items bind the source row, usage key, content type, byte size and actual-byte digest. Already retained V37 export snapshots remain read-only with their original bytes and metadata. The fresh reviewed-base and retained-evidence boundary is owned by [Version Control](version-control.md#selected-publication-storage-and-retained-operations). Derived runtime-consumed artifacts produced by domain services follow the same writer rule: @@ -255,7 +255,7 @@ The `game_assets` table stores ordinary design-time upload records. In the curre Future metadata-only storage may replace `data` with fields such as `storage_key`, `content_hash`, and `size_bytes`, but only if the new schema preserves the same repair invariant: Published/Active releases must be exactly reproducible for as long as their assets remain non-Retired or design-history reachable. -To associate assets with specific published versions while still allowing reuse across versions, Game Design uses a separate mapping table. Migration V37 implements `version_asset` and its tenant-qualified identity, uniqueness, and source-name constraints. The repository provides an owner-local `associateDraftAsset` operation, but no production caller currently creates mappings, so the Draft authoring producer remains absent. The following mapping contract is implemented at the schema/repository boundary where stated; it does not imply an available authoring ingress: +To associate assets with specific published versions while still allowing reuse across versions, Game Design uses a separate mapping table. Migration V37 implements `version_asset` and its tenant-qualified identity, uniqueness, and source-name constraints. The `ordinary_asset_snapshot_projection` trigger writes mappings only from a synchronized ordinary asset snapshot; the direct `associateDraftAsset` operation fails closed. Export snapshot creation requires the exact synchronized source through `requireExportSelection`, and a Version without asset genesis cannot freeze one. The controlled-input source-owner path has local PostgreSQL proof, while production authoring ingress remains unavailable. The following mapping contract is implemented at the schema/repository boundary where stated; it does not imply an available authoring ingress: - `version_asset`: - `tenant_id` – owning game @@ -308,7 +308,7 @@ The target record would be written only by Game Design's authorized owner-local Any state or epoch change before tombstoning, or any release-bundle/release-reachability evidence, invalidates or rejects the record. `TombstoneVersionAssets` must atomically consume a still-valid `RECORDED` proof while transitioning the matching `FAILED` artifact to `TOMBSTONED`; `BeginPurgeVersionAssets` must require the resulting `TOMBSTONE_CONSUMED` proof, matching `tombstone_state_epoch`, continued caller-tenant `FAILED` authority, and a fresh no-release-reachability/eligibility check. A failed candidate without this durable proof is not eligible, even when its artifact state is `FAILED` or `TOMBSTONED`. -Before the first byte is exported for a version, the workflow freezes an immutable durable per-version export snapshot. Migration V37 defines the `version_asset_export_snapshot` header and the `version_asset_export_item` projection keyed by `(tenant_id, version_id, usage_key)`, with selected `asset_id`, source content hash, byte size, and content type. V37 also protects a referenced row's ID, tenant, file name, content type, and bytes from changes and prevents its deletion; Draft source rows without a frozen reference remain mutable. Migration V38 adds candidate evidence columns to `version_asset_artifact`: `manifest_schema_version`, `artifact_digests_json`, `published_object_proofs_json`, and `candidate_snapshot_version_id`; V50 adds the frozen candidate delivery origin. The current implementation persists and independently reads this snapshot, freezes the currently mapped set (which may be empty because a production Draft mapping producer is absent), and verifies actual source byte hashes and lengths in the database on later metadata reads. The exporter then loads and verifies one bounded source payload at a time into private temporary files before any object-store write; payload heap usage does not grow with the complete selection. Immutable object readback compares bounded streams against that verified staging, including exact end-of-stream and declared length. The temporary staging is invocation-local and is removed on completion or failure; it is not a durable replacement repair source. Same-version exports and repair use the snapshot rather than re-selecting tenant assets or mutable mappings. Candidate evidence is persisted and independently read back before object writes. If source bytes nevertheless differ from the frozen digest, snapshot verification fails before object writes. +Before the first byte is exported for a version, the workflow freezes an immutable durable per-version export snapshot. Migration V37 defines the `version_asset_export_snapshot` header and the `version_asset_export_item` projection keyed by `(tenant_id, version_id, usage_key)`, with selected `asset_id`, source content hash, byte size, and content type. V37 also protects a referenced row's ID, tenant, file name, content type, and bytes from changes and prevents its deletion; Draft source rows without a frozen reference remain mutable. Migration V38 adds candidate evidence columns to `version_asset_artifact`: `manifest_schema_version`, `artifact_digests_json`, `published_object_proofs_json`, and `candidate_snapshot_version_id`; V50 adds the frozen candidate delivery origin. The current implementation calls `requireExportSelection` to require the exact synchronized ordinary source snapshot, including an explicitly owner-founded empty set, before creating an export snapshot. `ordinary_asset_snapshot_projection` writes the `version_asset` mappings from that source snapshot; a Version without asset genesis cannot freeze an export snapshot. The implementation verifies actual source byte hashes and lengths in the database on later metadata reads. The exporter then loads and verifies one bounded source payload at a time into private temporary files before any object-store write; payload heap usage does not grow with the complete selection. Immutable object readback compares bounded streams against that verified staging, including exact end-of-stream and declared length. The temporary staging is invocation-local and is removed on completion or failure; it is not a durable replacement repair source. Same-version exports and repair use the snapshot rather than re-selecting tenant assets or mutable mappings. Candidate evidence is persisted and independently read back before object writes. If source bytes nevertheless differ from the frozen digest, snapshot verification fails before object writes. The immutable candidate also freezes the approved public `/assets` base URL used to construct each manifest entry's absolute runtime `url`. The manifest hash commits to those URLs, so exact repair reuses the candidate's frozen origin instead of current mutable configuration. Candidate evidence does not authorize a different origin for delivery: the manifest URL remains the release-bound fetch location. Retained pre-origin candidates have no proven delivery origin; they remain unchanged and exact replay fails closed. Only exact verified attested manifest bytes could establish an origin for a separately authorized recovery; current mutable configuration is not evidence. @@ -353,7 +353,7 @@ Implementation notes: `GameAssetRepository` retains the service-local jOOQ/PostgreSQL boundary for previously accepted rows. `GameAssetServiceImpl` currently refuses uploads before repository access. -At publish time, the current private mechanics read bytes selected by the durable `version_asset` snapshot, hash the actual bytes, and write immutable content-addressed artifact and manifest keys. Before object writes they persist and independently read back candidate evidence containing the exact immutable object keys and digests; each write is followed by exact object readback. This path is non-ingress, and its reflective unit proof uses a mocked `PublishedReleaseBundleService`; it is not production publication proof. The mapping schema and snapshot are live, but no production Draft authoring caller currently creates mappings, so this path does not select arbitrary tenant assets and may export an empty mapped set. Duplicate usage keys and the reserved `manifest.json` key fail closed before object writes. This implementation evidence does not establish a private-candidate isolation boundary, a production public origin, owner authorization for external delivery, database lifecycle CAS, or runtime delivery proof. Target runtime clients load branding and theme resources through the approved public `/assets/**` origin using the manifest; the current Gateway has no `/assets/**` route, and external delivery remains unproved pending an approved public origin/provisioner. The Game Design Service remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. +At publish time, the current private mechanics require the exact synchronized ordinary source snapshot through `requireExportSelection`, then read the bytes selected by its durable `version_asset` projection, hash the actual bytes, and write immutable content-addressed artifact and manifest keys. A Version without asset genesis cannot freeze an export snapshot, and only an explicitly owner-founded empty source snapshot can yield an empty selection. Before object writes the mechanics persist and independently read back candidate evidence containing the exact immutable object keys and digests; each write is followed by exact object readback. This path is non-ingress, and its reflective unit proof uses a mocked `PublishedReleaseBundleService`; it is not production publication proof. The mapping schema and snapshot are live, but production authoring ingress remains unavailable. Direct `associateDraftAsset` calls fail closed, and this path does not select arbitrary tenant assets. Duplicate usage keys and the reserved `manifest.json` key fail closed before object writes. This implementation evidence does not establish a private-candidate isolation boundary, a production public origin, owner authorization for external delivery, database lifecycle CAS, or runtime delivery proof. Target runtime clients load branding and theme resources through the approved public `/assets/**` origin using the manifest; the current Gateway has no `/assets/**` route, and external delivery remains unproved pending an approved public origin/provisioner. The Game Design Service remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. Current repair reads the frozen source snapshot and persisted candidate independently, verifies source bytes and candidate object proofs, and matches the complete candidate against the published release bundle before writing any object. It then rewrites only the exact content-addressed object and manifest keys. The candidate is not isolated in a private staging namespace, and the target global publication/purge fence and physical object-store proof remain absent; immutable keys and pre-write attestation checks do not establish those broader guarantees. @@ -365,7 +365,7 @@ In the target contract, the `published_release_bundle` attestation must referenc ### Interaction with Script-Only Patches -Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. Published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current implementation persists that binding and snapshot, but its `associateDraftAsset` authoring operation has no production caller. Export therefore uses only existing mappings and does not select every tenant asset as a fallback. Same-version export reads the durable snapshot across process restarts; asset authoring remains incomplete until a production mapping producer exists. +Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. Published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current implementation persists that binding and snapshot after `requireExportSelection` verifies the exact synchronized ordinary source snapshot; `ordinary_asset_snapshot_projection` is the only mapping writer, and direct `associateDraftAsset` calls fail closed. A Version without asset genesis cannot freeze an export snapshot, and export does not select every tenant asset as a fallback. Same-version export reads the durable snapshot across process restarts; production authoring ingress remains unavailable. ### Asset Lifecycle and Publish Workflow @@ -418,15 +418,15 @@ Transition enforcement contract: - `PUBLISHED` is the only success state that may be treated as launchable. Object-store bytes in `STAGED` or `EXPORTED_UNATTESTED` are not publish-complete on their own. - For each `(tenantId, versionId)` the durable publish workflow runs an `ExportAssets` step that: - - **Current implementation:** reads the durable per-version snapshot created from `version_asset` mappings and obtains bytes from `game_assets.data`. Migration V37 and the repository implement the mapping and snapshot tables, but `associateDraftAsset` has no production caller, so the Draft authoring producer that creates mappings is absent. The exporter does not include unmapped tenant assets; the mapped selection may be empty. + - **Current implementation:** `requireExportSelection` requires the exact synchronized ordinary source snapshot before the repository freezes a per-version snapshot and reads bytes from `game_assets.data`. `ordinary_asset_snapshot_projection` writes `version_asset` mappings only from that source snapshot; direct `associateDraftAsset` calls fail closed. A Version without asset genesis cannot freeze an export snapshot, and only an explicitly owner-founded empty source snapshot can produce an empty selection. Production authoring ingress remains unavailable, and the exporter does not include unmapped tenant assets. - **Target convergence:** freezes a persisted selection from `version_asset` joined to `game_assets` for the target `(tenantId, versionId)`; unmapped tenant assets are excluded from that version's export. The candidate is built privately, every selected byte is SHA-256 hashed, and the verified manifest and objects receive immutable content-addressed keys before public delivery. - Copies the selected ordinary asset bytes from `game_assets.data` (or a future equivalent immutable repair source) into private candidate storage, verifies the complete candidate, and only then publishes immutable content-addressed objects. A tenant/version prefix may remain a delivery grouping, but it is not the object identity or lifecycle authority. - Writes the version-scoped `manifest.json` as a content-addressed immutable object after candidate verification; it must not overwrite an attested manifest key. - Updates version metadata with the manifest location. - Transitions `version_asset_artifact` from `STAGED` to `EXPORTED_UNATTESTED`. - - **Mapping validation:** the repository validates the mapped source rows and their uniqueness while freezing the snapshot. A production Draft authoring producer remains needed to create mappings through the owner-local operation; this status does not imply an upload-to-version association ingress. + - **Mapping validation:** the repository validates the projected source rows and their uniqueness while freezing the snapshot. Snapshot creation requires the exact synchronized source through `requireExportSelection`, and a Version without asset genesis cannot freeze one. Only the synchronized ordinary source snapshot projection writes mappings; the direct owner-local association operation fails closed. Production authoring ingress remains unavailable, and this status does not imply an upload-to-version association ingress. - **Target-state retry behavior:** Once the frozen export snapshot exists, rerunning `ExportAssets` for the same `(tenantId, versionId)` reuses that snapshot, recomputes and verifies the same content-addressed bytes, and leaves the version metadata consistent. It must not re-select assets after the snapshot is frozen, and it must not overwrite an attested public key. Changed bytes require a new key and release version. -- **Current implementation boundary:** `AssetExportServiceImpl` reads and independently verifies the durable per-version source snapshot, and the candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Published repair independently reads the existing candidate and requires its manifest, artifact digests, and object keys to match the release attestation before any object write. V37 protects a `game_assets` row's ID, tenant, file name, content type, and bytes from changes and prevents deletion while a frozen item references it; snapshot readback also detects any source bytes that nevertheless differ from the frozen digest. The absent production Draft mapping producer remains the authoring gap, and physical object-store repair proof remains unavailable. +- **Current implementation boundary:** `AssetExportServiceImpl` reads and independently verifies the durable per-version source snapshot, which can be frozen only after `requireExportSelection` confirms the exact synchronized ordinary source snapshot; a Version without asset genesis cannot freeze it. `ordinary_asset_snapshot_projection` is the only writer of `version_asset` mappings, and direct `associateDraftAsset` calls fail closed. The candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Published repair independently reads the existing candidate and requires its manifest, artifact digests, and object keys to match the release attestation before any object write. V37 protects a `game_assets` row's ID, tenant, file name, content type, and bytes from changes and prevents deletion while a frozen item references it; snapshot readback also detects any source bytes that nevertheless differ from the frozen digest. Production authoring ingress remains unavailable, and physical object-store repair proof remains unavailable. - A later `FinalizePublishedRelease` step must read the computed `manifestHash`, write `published_release_bundle`, and only then transition `version_asset_artifact` from `EXPORTED_UNATTESTED` to `PUBLISHED`. If the attestation write has a lost or ambiguous response, the artifact remains `EXPORTED_UNATTESTED` and reconciliation-required; it may move to `FAILED` only after exact readback proves that no `published_release_bundle` exists for the tenant/version at all and no unresolved attestation write or cleanup ambiguity remains. Any existing row, including a mismatched attestation, keeps the artifact nonterminal until owner reconciliation determines the outcome; a matching committed attestation permits reconciliation to `PUBLISHED` and never `FAILED`. Implementations must not expose launchable `PUBLISHED` assets without a matching release attestation. - The `EXPORTED_UNATTESTED` readback and any transition to `FAILED` must be serialized against concurrent publication for the same `(tenantId, versionId)`. The owner transaction (or one shared lifecycle CAS/lock fence held across the readback and state transition) must lock or compare the artifact row and exact `published_release_bundle` identity together, re-read the bundle immediately before deciding `FAILED`, and reject a stale state epoch. A matching bundle that committed before or during the readback reconciles the artifact to `PUBLISHED`; a missing bundle can transition to `FAILED` only when the same fenced readback proves no publication committed and no external write remains ambiguous. A later failure must never demote a matching publication or delete its version/assets. - Current private failure handling revalidates the pending attempt and requires its local readback to prove no bundle exists, either no artifact exists or an exact empty `STAGED` artifact has no recorded candidate, and Version remains `DRAFT` before marking failure; it retains Version and does not compensate by deleting it. A committed, partial, or ambiguous readback remains reconciliation-required, while best-effort candidate cleanup is attempted after the transaction and physical deletion is currently hard-disabled. This private path remains inaccessible through public fresh/`PENDING` ingress and does not establish a global lifecycle fence, rollback/ambiguous-commit recovery, or physical object-store proof. Target recovery still requires committed-bundle, exact-absence, and lost-response proof under the shared fence. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 75ccedb7cf..cf1d42b8fb 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -258,3 +258,9 @@ Entry format: - Observation: the run retained immutable authored-world source receipts while its PostgreSQL volume was rebuilt, so Game Design correctly rejected the new database owner evidence as conflicting with the old receipt. Reusing the ownership capability did not make the two database histories one proof. - Expected pattern: allocate a new run ID and ownership token for a new fresh-database proof; preserve the prior receipt and use canonical run-owned teardown. Use the restart entrypoint when proving continuity of an existing deployment. Do not delete receipt evidence to make a reused fresh-bootstrap identity succeed or credit a setup failure as runtime proof. - Current status: the reused-identity invocation failed and was canonically torn down; a unique-identity invocation rebuilt current jars and images, passed both WebSocket and Telnet player-flow baselines, and completed canonical teardown. + +- `2026-10-14`: Qualify receiver counts to their published CLI1 and current CLI2 postimages + - Context: the preceding 63-path/127-PostgreSQL observation describes the earlier reconstruction, whose historical source and parent attribution is retained in the tracker; it does not describe the current receiver. The published CLI1 receiver `24b64275a756d9375d1e61ef7e53a353160a09a2` on parent `d7c8f84fa947644a651304205803c3919c81684e` owned 64 Game Design paths and had 502 unit and 128 physical PostgreSQL cases; the latest CLI2 receiver is based on parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b`. + - Observation: retain the 64/502/128 figures as CLI1 evidence for its published postimage. The current CLI2 tracker boundary is 65 Game Design paths with 503 unit and 128 physical PostgreSQL cases; the latest parent also includes new Account SQL. + - Expected pattern: tie each receiver count and proof to its exact postimage and parent; do not carry Account byte-identity claims across the new SQL or infer unrun exact-head CI or runtime proof. + - Current status: the tracker records the local CLI2 gate and its current attribution. This qualification adds no execution or proof. 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 0991926104..2521070488 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,17 +6,19 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the qualified Entity/Account preparation parent `d7c8f84fa947644a651304205803c3919c81684e` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 64 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The affected composition gate and fresh physical owner proofs pass with the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 65 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document, for 77 unique receiving paths. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. ### Coherent owner receiving prerequisite -The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. +The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. The latest parent corrects the unmerged Account V1003 tail; whole Account-input byte identity is not carried forward from the earlier preparation parent. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. -After the first CLI review's two accepted corrections, the consolidated Game Design and Logging full-service gate passes in 4 minutes 24 seconds with formatting, actual Game Design jOOQ generation, static analysis and documentation checks. Game Design freshly executes 502 unit cases and all 128 physical PostgreSQL cases with zero failures, errors or skips. The nine-case storage-upgrade suite includes typed transaction-ID projection across a synthetic epoch boundary, an actual enabled template-insert witness and rejection of a forged witness; it does not advance the PostgreSQL cluster through four billion transactions. Fresh and upgraded combined histories now contain 85 entries through V1025, with retained predecessor checksums and rows preserved. Logging's 272 unit and 25 PostgreSQL/service integration cases executed in the preceding gate on unchanged Logging inputs and remain up-to-date in the successful consolidated rerun. Issue and recovery accept an exact Account reference under a different issuer clock while retaining strict local expiry and complete response binding; Account's own issuance-lifetime enforcement remains unchanged. These owner and receiving proofs do not establish genuine production authority or rebuilt receiver activation. +The earlier published CLI1 receiver at `24b64275a756d9375d1e61ef7e53a353160a09a2`, on preparation parent `d7c8f84fa947644a651304205803c3919c81684e`, had 64 Game Design paths and retains its 502 unit-case and 128 physical PostgreSQL-case attribution. After the first CLI review's two accepted corrections, its consolidated Game Design and Logging full-service gate passed in 4 minutes 24 seconds with formatting, actual Game Design jOOQ generation, static analysis and documentation checks. The nine-case storage-upgrade suite included typed transaction-ID projection across a synthetic epoch boundary, an actual enabled template-insert witness and rejection of a forged witness; it did not advance the PostgreSQL cluster through four billion transactions. Fresh and upgraded combined histories contained 85 entries through V1025, with retained predecessor checksums and rows preserved. Logging's 272 unit and 25 PostgreSQL/service integration cases executed in the preceding gate on unchanged Logging inputs and remained up-to-date in that consolidated rerun. Issue and recovery accepted an exact Account reference under a different issuer clock while retaining strict local expiry and complete response binding; Account's own issuance-lifetime enforcement remained unchanged. These are CLI1 postimage results and do not establish genuine production authority or rebuilt receiver activation. -The complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passes formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executes 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executes all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history has 62 entries; upgrade and fresh histories have 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases keep their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verifies their unchanged inputs as up-to-date rather than relabeling them fresh. +The accepted CLI2 corrections passed the consolidated local Common/GDS gate in 4 minutes 52 seconds: 92 tasks completed, 35 executed and 57 up-to-date. Fresh XML attribution records 482 Common unit cases and 503 Game Design unit cases plus all 128 physical PostgreSQL cases, each with zero failures, errors or skips. The combined proof covers the Game Design ReviewedBase constructor cases and Flyway-derived migration tail assertions, and the Common canonical visibility and bounded-v2-size cases. Logging's 272 unit and 25 PostgreSQL/service integration cases retain their earlier execution attribution on unchanged inputs; this Common/GDS gate did not rerun them. On latest parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b`, the separate Account source proof reports 1,295 unit cases with four existing skips, 245 physical PostgreSQL cases with zero skips, and 20 focused enabled-guard cases; these results are qualified to that parent. This local gate does not establish published exact-head CI, Hosted review, genuine production authority or rebuilt receiver activation. -Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs remain byte-identical. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passes freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. Current parent `d7c8f84fa947644a651304205803c3919c81684e` changes only the review controller and its tests from `4925747`; all owner runtime and migration inputs remain byte-identical. The receiver carries those proofs with their original attribution, while exact-head CI and review remain separate. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. +Historical earlier-parent result: the complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passed formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executed 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executed all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history had 62 entries; upgrade and fresh histories had 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases retain their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verified their unchanged inputs as up-to-date rather than relabeling them fresh. This 63-path/127-case result is historical for that parent and is not the current 65-path/503-unit/128-PostgreSQL receiver proof. + +Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs were byte-identical at that parent. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passed freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. The previous preparation parent `d7c8f84fa947644a651304205803c3919c81684e` changed only the review controller and its tests from `4925747`; its owner runtime and migration byte-identity statement applies to that parent only. The newer parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` includes new Account SQL, so the earlier Account byte-identity statement does not apply to the latest parent. The receiver carries each parent proof with its original attribution, while exact-head CI and review remain separate. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. External Account/World inputs in the storage and source fixtures remain explicitly controlled. Current Java callers issue complete fresh-v2 operations; the decoder preserves original three-frame v1 bytes as read-only history without inventory authority. Installing source tables and proving owner-local behavior does not register a genuine producer, establish rebuilt runtime proof for the receiver, authorize activation or complete any Gameplay handoff. All four genuine handoffs, full publication, protected activation, Entity placement and operational-region delivery remain open; broader Unit 1B stays paused. The owning storage and reviewed-base contract is [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java index cdf1d221e6..b19ba8cd9a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java @@ -290,8 +290,10 @@ private static List parseEpochs( || !unit.scopeType().equals(epoch.scopeType()) || !unit.scopeId().equals(epoch.scopeId()) || !unit.expectedEpoch().equals(epoch.expectedEpoch()) - || new BigInteger(epoch.resultingEpoch()).compareTo(new BigInteger(epoch.expectedEpoch())) - <= 0) { + || !new BigInteger(epoch.expectedEpoch()) + .add(BigInteger.ONE) + .toString() + .equals(epoch.resultingEpoch())) { throw new IllegalArgumentException( "Applied owner tuple differs from the complete bound epoch declaration"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java new file mode 100644 index 0000000000..c4eae206bf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.gamedesign; + +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.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.Fence; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.Request; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; + +class DraftSynchronizedVisibilityEvidenceTest { + private static final String EXPECTED_EPOCH = "900719925474099312345678901234567890"; + private static final UUID REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID COMMIT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_REQUEST_ID = uuid("33333333-3333-4333-8333-333333333333"); + + @Test + void requiresExactlyOneAppliedEpochAdvanceAcrossLargeCounters() throws Exception { + BigInteger expected = new BigInteger(EXPECTED_EPOCH); + String nextEpoch = expected.add(BigInteger.ONE).toString(); + + DraftSynchronizedVisibilityEvidence evidence = evidence(nextEpoch); + evidence.requireValid(); + assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).appliedEpochs()) + .containsExactly( + new AppliedEpoch( + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + EXPECTED_EPOCH, + nextEpoch)); + + for (String invalidEpoch : + List.of( + expected.toString(), + expected.subtract(BigInteger.ONE).toString(), + expected.add(BigInteger.TWO).toString())) { + assertThatThrownBy(() -> evidence(invalidEpoch)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete bound epoch declaration"); + } + } + + private static DraftSynchronizedVisibilityEvidence evidence(String resultingEpoch) + throws Exception { + DraftCommitBinding binding = binding(); + Request request = new Request(1, "test", READ_REQUEST_ID, binding.target()); + Fence fence = + new Fence( + REQUEST_ID, + COMMIT_ID, + binding.digest(), + resultVector(binding, resultingEpoch), + OffsetDateTime.parse("2026-10-14T00:00:00Z")); + return new DraftSynchronizedVisibilityEvidence(request, binding, "SYNCHRONIZED", fence); + } + + private static String resultVector(DraftCommitBinding binding, String resultingEpoch) + throws Exception { + String resultBytes = Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8)); + String json = + "[{" + + "\"owner\":\"WORLD_MANAGEMENT\"," + + "\"status\":\"APPLIED\"," + + "\"commitId\":\"" + + COMMIT_ID + + "\"," + + "\"bindingDigest\":\"" + + binding.digest() + + "\"," + + "\"resultIdentity\":\"world-result-1\"," + + "\"resultBytesBase64\":\"" + + resultBytes + + "\"," + + "\"appliedEpochs\":[{" + + "\"aggregateType\":\"WORLD_TEMPLATE\"," + + "\"aggregateId\":\"world-23\"," + + "\"scopeType\":\"ROOM_SCOPE\"," + + "\"scopeId\":\"room-scope-3\"," + + "\"expectedEpoch\":\"" + + EXPECTED_EPOCH + + "\"," + + "\"resultingEpoch\":\"" + + resultingEpoch + + "\"}]}]"; + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } + + private static DraftCommitBinding binding() { + return DraftCommitBinding.create( + new TargetProof( + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + 1, + "test-tenant", + 2, + "test-tenant", + "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-commit-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{\"world\":true}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + EXPECTED_EPOCH))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java index 5672a7ac49..3f3da42652 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java @@ -51,11 +51,13 @@ void absentInventoryWrongDigestTrailingAndOversizeInputsDeny() throws Exception assertThatThrownBy( () -> GameDesignPublicationOperationBinding.fromStored(trailing.toByteArray())) .isInstanceOf(IllegalArgumentException.class); + var oversize = prefix(operation, GameDesignPublicationOperationBinding.SCHEMA); + oversize.write( + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1 - oversize.size()]); assertThatThrownBy( - () -> - GameDesignPublicationOperationBinding.fromStored( - new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) - .isInstanceOf(IllegalArgumentException.class); + () -> GameDesignPublicationOperationBinding.fromStored(oversize.toByteArray())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete bounded v2"); } @Test 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 index 6995dc8f3a..c5f7228fb2 100644 --- 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 @@ -217,6 +217,9 @@ public record ReviewedBaseReadback(byte[] canonicalBytes, String digest, String schema = Objects.requireNonNull(schema, "schema"); if (!isSupportedSchema(schema)) throw new IllegalArgumentException("Unsupported reviewed-base evidence schema"); + if (!schema.equals(new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes).text())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); + } if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(digest)) { throw new IllegalArgumentException("REVIEWED_BASE_STORED_DIGEST_CONFLICT"); } 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 index 1435552d5e..c22ef806c2 100644 --- 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 @@ -252,7 +252,7 @@ public Optional readCapture(GameDesignPublicationOperation operation) { new GameDesignReviewedBaseRepository(dsl) .requireRetained(operation.account().input().selection().selectedCommit()); } - if (command.isEmpty() || policy.isEmpty() || asset.isEmpty() && !historical) { + if (command.isEmpty() || policy.isEmpty() || (asset.isEmpty() && !historical)) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow(), asset)); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index 371decc5d4..e3f73cbc8f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -147,6 +147,7 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); + var expectedMigrations = migrationExpectations(source, schema); flyway(source, schema, null).migrate(); flyway(source, schema, null).validate(); var dsl = DSL.using(source, SQLDialect.POSTGRES); @@ -154,12 +155,12 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua dsl.fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(85L); + .isEqualTo((long) expectedMigrations.versionedCount()); assertThat( dsl.fetchSingle( "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") .get(0, Integer.class)) - .isEqualTo(1025); + .isEqualTo(expectedMigrations.highestIntegerVersion()); assertEnabledGuards(dsl, schema); } @@ -188,6 +189,7 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageT .getValues(0, String.class); assertThat(history).hasSize(62); var rows = retainedRows(fixture); + var expectedMigrations = migrationExpectations(fixture.source(), fixture.schema()); // The service's actual startup locations and default ordering must upgrade this parent. flyway(fixture.source(), fixture.schema(), null).migrate(); @@ -206,7 +208,7 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageT .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(85L); + .isEqualTo((long) expectedMigrations.versionedCount()); assertThat(retainedRows(fixture)).isEqualTo(rows); assertEnabledGuards(fixture); } @@ -222,6 +224,7 @@ void fullStorageUpgradeRetainsParentV1RowsBytesChecksumsAndOwnerReads() throws E var migrationHistory = predecessorChecksums(fixture); assertThat(migrationHistory).hasSize(59); var beforeRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + var expectedMigrations = migrationExpectations(fixture.source(), fixture.schema()); assertThatThrownBy(operation::inventory) .isInstanceOf(IllegalStateException.class) .hasMessage("HISTORICAL_PUBLICATION_INVENTORY_UNAVAILABLE"); @@ -235,7 +238,7 @@ void fullStorageUpgradeRetainsParentV1RowsBytesChecksumsAndOwnerReads() throws E .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(85L); + .isEqualTo((long) expectedMigrations.versionedCount()); assertThat(retainedRows(fixture)).isEqualTo(rows); assertThat(GameDesignPublicationOperation.fromStored(original).canonicalBytes()) .containsExactly(original); @@ -325,6 +328,7 @@ void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() assertThat(beforeRead.canonicalBytes()).containsExactly(originalBytes); assertThat(beforeRead.digest()).isEqualTo(originalDigest); var parentChecksums = predecessorChecksums(fixture); + var expectedMigrations = migrationExpectations(fixture.source(), fixture.schema()); upgrade(fixture); @@ -334,14 +338,14 @@ void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() .fetchSingle( "SELECT max(version::int) FROM flyway_schema_history_game_design_service WHERE version ~ '^[0-9]+$'") .get(0, Integer.class)) - .isEqualTo(1025); + .isEqualTo(expectedMigrations.highestIntegerVersion()); assertThat( fixture .dsl() .fetchSingle( "SELECT count(*) FROM flyway_schema_history_game_design_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(85L); + .isEqualTo((long) expectedMigrations.versionedCount()); assertThat(predecessorChecksums(fixture)).isEqualTo(parentChecksums); assertThat(reviewedBaseRow(fixture, binding)).isEqualTo(beforeRow); var retained = new GameDesignReviewedBaseRepository(fixture.dsl()).read(binding).orElseThrow(); @@ -957,6 +961,22 @@ private Flyway flyway( return builder.load(); } + private MigrationExpectations migrationExpectations( + DriverManagerDataSource source, String schema) { + var versionedMigrations = + Arrays.stream(flyway(source, schema, null).info().all()) + .filter(migration -> migration.getVersion() != null) + .toList(); + int highestIntegerVersion = + versionedMigrations.stream() + .map(migration -> migration.getVersion().getVersion()) + .filter(version -> version.matches("[0-9]+")) + .mapToInt(Integer::parseInt) + .max() + .orElseThrow(); + return new MigrationExpectations(versionedMigrations.size(), highestIntegerVersion); + } + private void upgrade(Fixture fixture) { flyway(fixture.source(), fixture.schema(), null).migrate(); flyway(fixture.source(), fixture.schema(), null).validate(); @@ -1376,4 +1396,6 @@ private record Fixture( TransactionTemplate write, GameDesignPublicationOperation operation, GameDesignPublicationOperationRepository operations) {} + + private record MigrationExpectations(int versionedCount, int highestIntegerVersion) {} } 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 index 7e386d4356..771254360e 100644 --- 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 @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftBaseReference; @@ -56,18 +57,69 @@ void genesisBindsPolicyCommandAndDistinctAssetBaselineWithoutCommit() { @Test void readbackRejectsChangedDigestAndDefensivelyCopiesBytes() { - byte[] bytes = {1, 2, 3}; + byte[] bytes = framedEvidence(GameDesignReviewedBaseEvidence.SCHEMA); var retained = new GameDesignReviewedBaseRepository.ReviewedBaseReadback( bytes, DraftAuthorizationFenceBinding.digest(bytes)); - bytes[0] = 9; - assertThat(retained.canonicalBytes()).containsExactly(1, 2, 3); + bytes[bytes.length - 1] ^= 1; + assertThat(retained.canonicalBytes()).isNotEqualTo(bytes); assertThatThrownBy( () -> new GameDesignReviewedBaseRepository.ReviewedBaseReadback(bytes, retained.digest())) .isInstanceOf(IllegalArgumentException.class); } + @Test + void readbackRequiresSupportedSchemaToMatchTheFirstEvidenceFrame() { + byte[] historical = framedEvidence(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + String historicalDigest = DraftAuthorizationFenceBinding.digest(historical); + var retainedHistorical = + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + historical, historicalDigest, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + assertThat(retainedHistorical.schema()) + .isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + historical, historicalDigest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); + + byte[] current = framedEvidence(GameDesignReviewedBaseEvidence.SCHEMA); + String currentDigest = DraftAuthorizationFenceBinding.digest(current); + var retainedCurrent = + new GameDesignReviewedBaseRepository.ReviewedBaseReadback(current, currentDigest); + assertThat(retainedCurrent.schema()).isEqualTo(GameDesignReviewedBaseEvidence.SCHEMA); + assertThat( + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + current, currentDigest, GameDesignReviewedBaseEvidence.SCHEMA) + .canonicalBytes()) + .containsExactly(current); + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + current, currentDigest, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); + + byte[] truncated = {0, 0, 0}; + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + truncated, + DraftAuthorizationFenceBinding.digest(truncated), + GameDesignReviewedBaseEvidence.SCHEMA)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Truncated immutable source frame"); + } + + private static byte[] framedEvidence(String schema) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, "opaque retained evidence"); + return out.toByteArray(); + } + private static GameDesignSourceRepository.Genesis genesis( TargetProof target, UUID receipt, String witness, UUID assetReceipt) { return new GameDesignSourceRepository.Genesis( From dd45c5778fc017267a77e36677d67fac9d84cb68 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:00:45 +1300 Subject: [PATCH 6/9] Fix asset source metadata readback and receiver review findings --- .../logging-admin-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 8 +- ...ame-authoring-publishing-and-activation.md | 12 +-- .../publication/AssetSourceRepository.java | 21 ++++- ...__template_config_verifier_diagnostics.sql | 87 +++++++++++++++++++ ...meDesignSourcePostgresIntegrationTest.java | 79 +++++++++++++++++ 6 files changed, 195 insertions(+), 14 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 741cdcec8e..c9d496764e 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -12,7 +12,7 @@ Implementation status: the claim-evidence receiver and Account read client exist When enabled, the Spring composition requires the configured canonical workload namespace and readable file-backed client mTLS inputs, initializes the typed Account client through the managed bean lifecycle, and connects it to the existing durable reservation service. The configuration supplies no reservation or authority source and exposes no external route. Its context test uses a controlled channel factory and test-only placeholder TLS files; it does not prove physical mTLS, production service startup, remote Account availability, or execution through Game Session launch selection and World activation. The target authorization and owner-forwarding rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). -Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple with its exact reserved operation and validated response, persists those unchanged Account bytes, and independently reads back the same durable authorization before advancing the one-time owner handoff. Exact retries may observe secret-free durable state but never return another transient reference or dispatch again. Ambiguous Account calls, local completion, readback, or owner-pending transitions remain pending with no automatic replacement issuance or rearming. ISSUE, RECOVER, and owner forwarding require no ambient SQL transaction or synchronization. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns original tuple and capture-reference binding; this local receiving boundary does not activate operator ingress or replace Account current-authority and expiry decisions. +Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple with its exact reserved operation and validated response, persists those unchanged Account bytes, and independently reads back the same durable authorization before advancing the one-time owner handoff. Exact retries may observe secret-free durable state but never return another transient reference or dispatch again. Ambiguous Account calls, local completion, readback, or owner-pending transitions remain pending with no automatic replacement issuance or rearming. ISSUE, RECOVER, and owner forwarding reject an ambient SQL transaction or transaction synchronization before any remote call. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns original tuple and capture-reference binding; this local receiving boundary does not activate operator ingress or replace Account current-authority and expiry decisions. The receiving client requires the returned expiry to be strictly later than its local clock and exactly equal to the authenticated Account bundle's expiry. Account enforces reference lifetime against its own issuance timestamp; Logging does not infer that lifetime from a different host's current clock or add a numerical skew allowance. Account projection evaluation time remains source-capture evidence rather than an issuance timestamp. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index cf1d42b8fb..3ba72ef05b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -250,7 +250,7 @@ Entry format: - `2026-10-14`: Qualify a receiving boundary from all current postimages and actual owner dependencies - Context: the Document receiving reconstruction initially inventoried only the published delta and untracked additions, omitting modified tracked source. Treating additive storage guards as passive also missed the fresh-v2 callers and ordinary asset source owner required by current positive publication tests. - Observation: the complete preserved delta had 84 paths, with a coherent 63-path Game Design boundary after inherited Account/process and separate Logging paths were accounted for. Current-owner proof required actual asset genesis, reviewed evidence and synchronized projection; decoding retained v1 history could not substitute for those callers. PostgreSQL's unnamed constraint identity also differed from jOOQ's H2 metadata emulation. - - Expected pattern: inventory committed, modified tracked and untracked postimages together, then reconcile actual imports and owner invariants on the selected parent. Keep retained-byte proof separate from current positive owner proof. Use targeted jOOQ ignore markers only for procedural or constraint blocks that do not change generated columns, with independent PostgreSQL upgrade and current-owner proof. + - Expected pattern: inventory committed, modified tracked and untracked postimages together, then reconcile actual imports and owner invariants on the selected parent. Keep retained-byte proof separate from current positive owner proof. Use targeted jOOQ ignore markers only for procedural or constraint blocks that do not change generated columns, with independent PostgreSQL upgrade and current-owner proof. Tie each proof count to its recorded postimage and parent; the historical counts here are examples, and current execution totals belong solely in the [owning implementation tracker](implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). - Current status: the complete 63-path Game Design receiver on the preparation parent passes its canonical gate, including all 127 physical PostgreSQL cases without skips. This does not establish genuine cross-service producer authority or packaged runtime proof. - `2026-10-14`: Fresh database proof needs a new run identity @@ -258,9 +258,3 @@ Entry format: - Observation: the run retained immutable authored-world source receipts while its PostgreSQL volume was rebuilt, so Game Design correctly rejected the new database owner evidence as conflicting with the old receipt. Reusing the ownership capability did not make the two database histories one proof. - Expected pattern: allocate a new run ID and ownership token for a new fresh-database proof; preserve the prior receipt and use canonical run-owned teardown. Use the restart entrypoint when proving continuity of an existing deployment. Do not delete receipt evidence to make a reused fresh-bootstrap identity succeed or credit a setup failure as runtime proof. - Current status: the reused-identity invocation failed and was canonically torn down; a unique-identity invocation rebuilt current jars and images, passed both WebSocket and Telnet player-flow baselines, and completed canonical teardown. - -- `2026-10-14`: Qualify receiver counts to their published CLI1 and current CLI2 postimages - - Context: the preceding 63-path/127-PostgreSQL observation describes the earlier reconstruction, whose historical source and parent attribution is retained in the tracker; it does not describe the current receiver. The published CLI1 receiver `24b64275a756d9375d1e61ef7e53a353160a09a2` on parent `d7c8f84fa947644a651304205803c3919c81684e` owned 64 Game Design paths and had 502 unit and 128 physical PostgreSQL cases; the latest CLI2 receiver is based on parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b`. - - Observation: retain the 64/502/128 figures as CLI1 evidence for its published postimage. The current CLI2 tracker boundary is 65 Game Design paths with 503 unit and 128 physical PostgreSQL cases; the latest parent also includes new Account SQL. - - Expected pattern: tie each receiver count and proof to its exact postimage and parent; do not carry Account byte-identity claims across the new SQL or infer unrun exact-head CI or runtime proof. - - Current status: the tracker records the local CLI2 gate and its current attribution. This qualification adds no execution or proof. 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 2521070488..e4ed5675ea 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,17 +6,19 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 65 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document, for 77 unique receiving paths. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. Published exact-head CI, Hosted/CLI review and rebuilt packaged receiver proof remain separate gates; earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 66 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document, for 78 unique receiving paths. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. The published CLI2 source `371f0dcedc75690aadb7cb267b4a19ddbc8c16ff` passed its exact-head Validation, CodeQL, License and Security gates. Current review fixes require new published-source CI; Hosted/CLI review and rebuilt packaged receiver proof remain separate gates. Earlier results retain their original source attribution. ### Coherent owner receiving prerequisite -The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. The latest parent corrects the unmerged Account V1003 tail; whole Account-input byte identity is not carried forward from the earlier preparation parent. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. +The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. Forward [V1026](../../../services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql) changes only five template-config verifier diagnostic prefixes; its predecessor function and migration bytes remain unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. The latest parent corrects the unmerged Account V1003 tail; whole Account-input byte identity is not carried forward from the earlier preparation parent. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. The earlier published CLI1 receiver at `24b64275a756d9375d1e61ef7e53a353160a09a2`, on preparation parent `d7c8f84fa947644a651304205803c3919c81684e`, had 64 Game Design paths and retains its 502 unit-case and 128 physical PostgreSQL-case attribution. After the first CLI review's two accepted corrections, its consolidated Game Design and Logging full-service gate passed in 4 minutes 24 seconds with formatting, actual Game Design jOOQ generation, static analysis and documentation checks. The nine-case storage-upgrade suite included typed transaction-ID projection across a synthetic epoch boundary, an actual enabled template-insert witness and rejection of a forged witness; it did not advance the PostgreSQL cluster through four billion transactions. Fresh and upgraded combined histories contained 85 entries through V1025, with retained predecessor checksums and rows preserved. Logging's 272 unit and 25 PostgreSQL/service integration cases executed in the preceding gate on unchanged Logging inputs and remained up-to-date in that consolidated rerun. Issue and recovery accepted an exact Account reference under a different issuer clock while retaining strict local expiry and complete response binding; Account's own issuance-lifetime enforcement remained unchanged. These are CLI1 postimage results and do not establish genuine production authority or rebuilt receiver activation. The accepted CLI2 corrections passed the consolidated local Common/GDS gate in 4 minutes 52 seconds: 92 tasks completed, 35 executed and 57 up-to-date. Fresh XML attribution records 482 Common unit cases and 503 Game Design unit cases plus all 128 physical PostgreSQL cases, each with zero failures, errors or skips. The combined proof covers the Game Design ReviewedBase constructor cases and Flyway-derived migration tail assertions, and the Common canonical visibility and bounded-v2-size cases. Logging's 272 unit and 25 PostgreSQL/service integration cases retain their earlier execution attribution on unchanged inputs; this Common/GDS gate did not rerun them. On latest parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b`, the separate Account source proof reports 1,295 unit cases with four existing skips, 245 physical PostgreSQL cases with zero skips, and 20 focused enabled-guard cases; these results are qualified to that parent. This local gate does not establish published exact-head CI, Hosted review, genuine production authority or rebuilt receiver activation. -Historical earlier-parent result: the complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passed formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executed 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executed all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history had 62 entries; upgrade and fresh histories had 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases retain their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verified their unchanged inputs as up-to-date rather than relabeling them fresh. This 63-path/127-case result is historical for that parent and is not the current 65-path/503-unit/128-PostgreSQL receiver proof. +The CLI3/first Hosted fix batch passed Game Design formatting, actual jOOQ generation, compilation, static checks and all 503 unit and 129 physical PostgreSQL cases with zero failures, errors or skips. The four-minute-five-second combined invocation failed only two newly added tracker link targets; those targets were corrected and the final documentation gate was run separately. The new physical case preserves enabled ordinary-source immutability guards: byte, content-type, file-name and null writes are rejected with SQLSTATE `23514`, and each subsequent synchronized read returns the same complete snapshot. Normal readback computes digest and size in PostgreSQL rather than transferring every source payload to Java; locked source-write qualification remains unchanged. Fresh and retained-history upgrade proof installs 86 migration entries through V1026 while preserving predecessor rows and checksums. The parent-pinned migration checker passes twelve sets and 295 versioned files. Common's 482 cases and Logging's 272 unit/25 integration cases retain their preceding execution attribution; this Game Design gate did not rerun them. These results do not establish genuine producer authority or rebuilt packaged receiver activation. + +Historical earlier-parent result: the complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passed formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executed 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executed all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history had 62 entries; upgrade and fresh histories had 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases retain their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verified their unchanged inputs as up-to-date rather than relabeling them fresh. This 63-path/127-case result is historical for that parent and is not the current 66-path/503-unit/129-PostgreSQL receiver proof. Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs were byte-identical at that parent. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passed freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. The previous preparation parent `d7c8f84fa947644a651304205803c3919c81684e` changed only the review controller and its tests from `4925747`; its owner runtime and migration byte-identity statement applies to that parent only. The newer parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` includes new Account SQL, so the earlier Account byte-identity statement does not apply to the latest parent. The receiver carries each parent proof with its original attribution, while exact-head CI and review remain separate. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. @@ -100,8 +102,8 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.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); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `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` 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-1.4` Game-authored assets, branding, and release manifests | `partial` | Partial at the current receiving boundary: ordinary asset-source creation and synchronized asset projection are present, while direct Draft association fails closed. Production authoring ingress and full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [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); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [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); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.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. Production authoring ingress 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. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | +| `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); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.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); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.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. | diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java index 7cae074cca..93727d3337 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -472,7 +472,7 @@ private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualify( private void verifyItems(AssetSnapshot snapshot) { for (var item : snapshot.items()) { - if (!item.equals(qualify(item.reference(), false))) + if (!item.equals(qualifyMetadata(item.reference()))) throw new IllegalStateException("ASSET_SOURCE_BYTE_READBACK_CONFLICT"); var r = item.reference(); var row = @@ -496,6 +496,25 @@ private void verifyItems(AssetSnapshot snapshot) { } } + private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualifyMetadata( + AssetSource.Reference reference) { + var target = reference.sourceBinding().target(); + var row = + dsl.fetchOne( + "SELECT file_name, content_type, 'sha256:' || encode(sha256(data), 'hex') AS digest, " + + "octet_length(data)::BIGINT AS byte_size FROM game_assets " + + "WHERE tenant_id = ? AND id = ? AND data IS NOT NULL", + target.gameDesignVersionTenantKey(), + Long.parseLong(reference.assetRowId())); + if (row == null || !reference.usageKey().equals(row.get("file_name", String.class))) + throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); + return new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, + row.get("content_type", String.class), + row.get("digest", String.class), + row.get("byte_size", Long.class)); + } + private Record head(TargetProof target) { return readHead(target, true); } diff --git a/services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql b/services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql new file mode 100644 index 0000000000..3b1e0dd26d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql @@ -0,0 +1,87 @@ +-- Correct verifier diagnostics while retaining the original migration history. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION verify_template_config_application_commit() RETURNS TRIGGER AS $$ +DECLARE branding_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; + declared BIGINT; retained BIGINT; declared_inventory BIGINT; retained_inventory BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_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 c 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 r 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 h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT count(*) INTO declared_inventory FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (x->>'payload')::JSONB->>'operation' = 'DECLARE_OWNER_SOURCE_INVENTORY'; + SELECT count(*) INTO retained FROM game_design_template_config_source_revision 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 count(*) INTO retained_inventory FROM game_design_template_config_owner_source_inventory_declaration + 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; + bytes := convert_to('game-design-template-config-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained + retained_inventory OR declared_inventory <> retained_inventory + OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'template config application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes 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 result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'template config mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'TEMPLATE_CONFIG_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'template config combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'template config scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'template config owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] 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 index cd257cf563..97454f83d5 100644 --- 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 @@ -33,6 +33,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -141,6 +142,84 @@ void ordinaryAssetSourceProjectsInheritedAndDeletedReferencesThroughCoordinatorF assertThat(fixture.dsl().fetchCount(DSL.table("version_asset"))).isZero(); } + @Test + void ordinaryAssetSourceRowsRejectChangesAndPreserveTheSynchronizedSnapshot() throws Exception { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + byte[] originalBytes = {0, 1, (byte) 0xff}; + long assetId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " + + "VALUES (?, 'logo.bin', 'application/octet-stream', ?) RETURNING id", + fixture.target().gameDesignVersionTenantKey(), + originalBytes) + .get(0, Long.class); + DraftCommitBinding upsert = + assetBinding( + fixture.target(), + "genesis:" + genesis.policy().receiptId(), + "0", + AssetSource.upsertPayload( + Long.toString(assetId), "logo.bin", AssetSource.Requiredness.REQUIRED)); + synchronize(fixture, upsert, apply(fixture, upsert)); + var snapshot = + fixture.sources().readSynchronized(fixture.target(), upsert.commitId()).orElseThrow(); + + assertAssetMutationDenied( + fixture, + upsert, + snapshot, + () -> + fixture + .dsl() + .execute("UPDATE game_assets SET data = ? WHERE id = ?", new byte[] {3}, assetId)); + assertAssetMutationDenied( + fixture, + upsert, + snapshot, + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET content_type = ? WHERE id = ?", "image/png", assetId)); + assertAssetMutationDenied( + fixture, + upsert, + snapshot, + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET file_name = ? WHERE id = ?", "renamed.bin", assetId)); + assertAssetMutationDenied( + fixture, + upsert, + snapshot, + () -> fixture.dsl().execute("UPDATE game_assets SET data = NULL WHERE id = ?", assetId)); + } + + private static void assertAssetMutationDenied( + Fixture fixture, + DraftCommitBinding binding, + GameDesignSourceRepository.SynchronizedSources snapshot, + Runnable mutation) { + assertThatThrownBy(mutation::run) + .rootCause() + .isInstanceOf(PSQLException.class) + .satisfies( + cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("ordinary asset source bytes are immutable from source history"); + }); + assertThat( + fixture.sources().readSynchronized(fixture.target(), binding.commitId()).orElseThrow()) + .isEqualTo(snapshot); + } + @Test void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() { Fixture fixture = fixture(); From 310532f10b8aa90d50e455e5ebc61a9c7e0b1cc2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:00:26 +1300 Subject: [PATCH 7/9] Unify asset metadata qualification and correct review proof attribution --- design/project-management/ai-observations.md | 8 ++++- ...ame-authoring-publishing-and-activation.md | 2 +- .../publication/AssetSourceRepository.java | 34 ++++--------------- 3 files changed, 15 insertions(+), 29 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3ba72ef05b..5af7120161 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -251,10 +251,16 @@ Entry format: - Context: the Document receiving reconstruction initially inventoried only the published delta and untracked additions, omitting modified tracked source. Treating additive storage guards as passive also missed the fresh-v2 callers and ordinary asset source owner required by current positive publication tests. - Observation: the complete preserved delta had 84 paths, with a coherent 63-path Game Design boundary after inherited Account/process and separate Logging paths were accounted for. Current-owner proof required actual asset genesis, reviewed evidence and synchronized projection; decoding retained v1 history could not substitute for those callers. PostgreSQL's unnamed constraint identity also differed from jOOQ's H2 metadata emulation. - Expected pattern: inventory committed, modified tracked and untracked postimages together, then reconcile actual imports and owner invariants on the selected parent. Keep retained-byte proof separate from current positive owner proof. Use targeted jOOQ ignore markers only for procedural or constraint blocks that do not change generated columns, with independent PostgreSQL upgrade and current-owner proof. Tie each proof count to its recorded postimage and parent; the historical counts here are examples, and current execution totals belong solely in the [owning implementation tracker](implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). - - Current status: the complete 63-path Game Design receiver on the preparation parent passes its canonical gate, including all 127 physical PostgreSQL cases without skips. This does not establish genuine cross-service producer authority or packaged runtime proof. + - Current status: the 63-path Game Design receiver on the earlier preparation parent passed its canonical gate, including all 127 physical PostgreSQL cases without skips. This historical result does not establish genuine cross-service producer authority or packaged runtime proof. Current receiver totals and proof belong in the [owning implementation tracker](implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). - `2026-10-14`: Fresh database proof needs a new run identity - Context: a supplementary Gameplay fresh-bootstrap proof reused a previously completed run identity after canonical teardown. - Observation: the run retained immutable authored-world source receipts while its PostgreSQL volume was rebuilt, so Game Design correctly rejected the new database owner evidence as conflicting with the old receipt. Reusing the ownership capability did not make the two database histories one proof. - Expected pattern: allocate a new run ID and ownership token for a new fresh-database proof; preserve the prior receipt and use canonical run-owned teardown. Use the restart entrypoint when proving continuity of an existing deployment. Do not delete receipt evidence to make a reused fresh-bootstrap identity succeed or credit a setup failure as runtime proof. - Current status: the reused-identity invocation failed and was canonically torn down; a unique-identity invocation rebuilt current jars and images, passed both WebSocket and Telnet player-flow baselines, and completed canonical teardown. + +- `2026-10-14`: Retain runtime ownership until teardown completes + - Context: a Gameplay source-built Compose proof passed both player-flow baselines, but its launcher generated the invocation token only in an ephemeral shell and did not include teardown before exiting. + - Observation: the wrapper left the owned project running, while its retained digest could no longer be matched with the lost token. Subsequent WSL memory and swap exhaustion coincided with local test timeouts; the contribution of other workloads was not established. An apparent WSL restart cleared swap and temporary logs but restarted the project's containers. + - Expected pattern: retain the invocation capability privately before launching, keep proof logs outside temporary storage when they must survive a restart, and include successful canonical teardown in the owned run boundary. A lost capability does not authorize rewriting ownership markers or reclaiming unrelated resources. + - Current status: Overseer is checking the exact owned project's labels, mounts and receipts for bounded recovery. The interrupted tests require fresh qualification; earlier successful transport proof remains attributed to its original source. 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 e4ed5675ea..620fe00cf3 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 @@ -102,7 +102,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.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); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `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` | Partial at the current receiving boundary: ordinary asset-source creation and synchronized asset projection are present, while direct Draft association fails closed. Production authoring ingress and full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [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); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [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); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.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. Production authoring ingress 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. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | +| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` only for controlled-input ordinary asset-source creation and synchronized projection, with focused proof in `GameDesignSourcePostgresIntegrationTest` and `VersionAssetExportSnapshotIntegrationTest`; production authoring ingress and the full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [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); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [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); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.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. Production authoring ingress 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. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | | `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); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.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); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.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. | diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java index 93727d3337..5cba3d29af 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -454,25 +454,24 @@ private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualify( var target = reference.sourceBinding().target(); var row = dsl.fetchOne( - "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?" + "SELECT file_name, content_type, 'sha256:' || encode(sha256(data), 'hex') AS digest, " + + "octet_length(data)::BIGINT AS byte_size FROM game_assets " + + "WHERE tenant_id = ? AND id = ? AND data IS NOT NULL" + (lock ? " FOR UPDATE" : ""), target.gameDesignVersionTenantKey(), Long.parseLong(reference.assetRowId())); - if (row == null - || !reference.usageKey().equals(row.get("file_name", String.class)) - || row.get("data", byte[].class) == null) + if (row == null || !reference.usageKey().equals(row.get("file_name", String.class))) throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); - byte[] bytes = row.get("data", byte[].class); return new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( reference, row.get("content_type", String.class), - CommandSource.sha256(bytes), - bytes.length); + row.get("digest", String.class), + row.get("byte_size", Long.class)); } private void verifyItems(AssetSnapshot snapshot) { for (var item : snapshot.items()) { - if (!item.equals(qualifyMetadata(item.reference()))) + if (!item.equals(qualify(item.reference(), false))) throw new IllegalStateException("ASSET_SOURCE_BYTE_READBACK_CONFLICT"); var r = item.reference(); var row = @@ -496,25 +495,6 @@ private void verifyItems(AssetSnapshot snapshot) { } } - private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualifyMetadata( - AssetSource.Reference reference) { - var target = reference.sourceBinding().target(); - var row = - dsl.fetchOne( - "SELECT file_name, content_type, 'sha256:' || encode(sha256(data), 'hex') AS digest, " - + "octet_length(data)::BIGINT AS byte_size FROM game_assets " - + "WHERE tenant_id = ? AND id = ? AND data IS NOT NULL", - target.gameDesignVersionTenantKey(), - Long.parseLong(reference.assetRowId())); - if (row == null || !reference.usageKey().equals(row.get("file_name", String.class))) - throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); - return new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( - reference, - row.get("content_type", String.class), - row.get("digest", String.class), - row.get("byte_size", Long.class)); - } - private Record head(TargetProof target) { return readHead(target, true); } From 7d007482de547fc4e3f02bb75842a5d83558c0a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:27:48 +1300 Subject: [PATCH 8/9] Preserve selected asset lifecycle updates and bound optional coverage upload --- .github/workflows/ci.yml | 2 + design/project-management/ai-observations.md | 8 +- ...dexes_and_selected_candidate_lifecycle.sql | 81 ++++++++ ...ionAssetExportSnapshotIntegrationTest.java | 174 ++++++++++++++++++ 4 files changed, 264 insertions(+), 1 deletion(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V1028__asset_history_indexes_and_selected_candidate_lifecycle.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c03ea3113e..ba38c4a2b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1057,6 +1057,8 @@ jobs: - name: ☂️ Upload Coverage to Codecov continue-on-error: true + # Optional coverage upload must leave time for required proof artifacts. + timeout-minutes: 2 uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: use_oidc: true diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5af7120161..45ff1b14bc 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -263,4 +263,10 @@ Entry format: - Context: a Gameplay source-built Compose proof passed both player-flow baselines, but its launcher generated the invocation token only in an ephemeral shell and did not include teardown before exiting. - Observation: the wrapper left the owned project running, while its retained digest could no longer be matched with the lost token. Subsequent WSL memory and swap exhaustion coincided with local test timeouts; the contribution of other workloads was not established. An apparent WSL restart cleared swap and temporary logs but restarted the project's containers. - Expected pattern: retain the invocation capability privately before launching, keep proof logs outside temporary storage when they must survive a restart, and include successful canonical teardown in the owned run boundary. A lost capability does not authorize rewriting ownership markers or reclaiming unrelated resources. - - Current status: Overseer is checking the exact owned project's labels, mounts and receipts for bounded recovery. The interrupted tests require fresh qualification; earlier successful transport proof remains attributed to its original source. + - Current status: Overseer verified bounded recovery and removed the completed project's containers and unused network, retaining volumes, backups and source. Normal serialized Gradle work resumed and the current Game Design checks passed; full local Compose remains paused while cleanup and whole-session ownership are corrected. Earlier successful transport proof remains attributed to its original source, and this recovery is not canonical full teardown or new-head packaged proof. + +- `2026-10-14`: Optional coverage upload can consume the validation job budget + - Context: the #3196 source Validation run completed its Game Design Gradle checks, runtime JAR and coverage artifact, then remained in the optional Codecov upload. + - Observation: the upload consumed the matrix job's 20-minute budget, cancelling the job and making the required Validation Gate red despite passing source checks. Metadata callbacks used a separate concurrency group and did not cause this cancellation; the slow upload's underlying cause remains unknown. + - Expected pattern: bound optional external uploads within the containing job's budget and preserve time for required proof artifacts. `continue-on-error` alone cannot protect against whole-job cancellation. Keep cancelled aggregate proof separate from successful individual checks. + - Current status: the Codecov step is bounded to two minutes with its existing failure tolerance retained. New-head cloud validation remains required to verify the workflow outcome. diff --git a/services/game-design-service/src/main/resources/db/migration/V1028__asset_history_indexes_and_selected_candidate_lifecycle.sql b/services/game-design-service/src/main/resources/db/migration/V1028__asset_history_indexes_and_selected_candidate_lifecycle.sql new file mode 100644 index 0000000000..827b396ce7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1028__asset_history_indexes_and_selected_candidate_lifecycle.sql @@ -0,0 +1,81 @@ +-- Support asset-row byte guards and foreign-key checks across retained source history. +CREATE INDEX idx_game_design_asset_source_revision_asset_id + ON game_design_asset_source_revision (asset_id) WHERE asset_id IS NOT NULL; + +CREATE INDEX idx_game_design_branding_source_revision_asset_id + ON game_design_branding_source_revision (asset_id) WHERE asset_id IS NOT NULL; + +-- Validate the original selected export workflow when evidence is first bound. +-- Later lifecycle workflows may change last_workflow_id while all candidate evidence stays frozen. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_asset_export_candidate_evidence() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.manifest_schema_version IS NOT NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN OLD; + END IF; + + IF NEW.manifest_schema_version IS NOT NULL + AND NEW.selected_candidate_version_id IS NULL + AND (TG_OP = 'INSERT' OR OLD.manifest_schema_version IS NULL) + AND NEW.candidate_public_base_url IS NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_ORIGIN_REQUIRED'; + END IF; + + IF NEW.selected_candidate_version_id IS NOT NULL + AND (TG_OP = 'INSERT' OR OLD.selected_candidate_version_id IS NULL) + AND NOT EXISTS ( + SELECT 1 + FROM version_asset_export_candidate c + JOIN version v ON v.tenant_id = c.tenant_id AND v.id = c.version_id + WHERE c.tenant_id = NEW.tenant_id + AND c.version_id = NEW.selected_candidate_version_id + AND c.request_digest = NEW.selected_candidate_request_digest + AND c.workflow_id = NEW.last_workflow_id + AND c.canonical_tenant_id = v.canonical_tenant_id + AND c.canonical_version_id = v.canonical_version_id + AND v.version_number = NEW.exported_version_number + AND c.manifest_schema_version = NEW.manifest_schema_version + AND c.manifest_hash = NEW.manifest_hash + AND c.manifest_hash = 'sha256:' || encode(sha256(c.manifest_bytes), 'hex') + AND c.artifact_digests_json::JSONB = NEW.artifact_digests_json::JSONB + AND c.required_usage_keys_json::JSONB = NEW.exported_manifest_asset_keys_json::JSONB + AND NEW.published_object_proofs_json::JSONB = ( + SELECT jsonb_agg( + jsonb_build_object('immutableObjectKey', proof.object_key, + 'contentDigest', proof.content_digest) + ORDER BY proof.object_key COLLATE "C", proof.content_digest COLLATE "C") + FROM ( + SELECT artifact->>'immutableObjectKey' AS object_key, + artifact->>'contentDigest' AS content_digest + FROM jsonb_array_elements(c.artifact_digests_json::JSONB) AS artifacts(artifact) + UNION + SELECT 'manifests/sha256/' || substring(c.manifest_hash FROM 8), c.manifest_hash + ) proof + ) + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' AND OLD.manifest_schema_version IS NOT NULL AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.exported_version_number IS DISTINCT FROM OLD.exported_version_number + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.manifest_schema_version IS DISTINCT FROM OLD.manifest_schema_version + OR NEW.artifact_digests_json IS DISTINCT FROM OLD.artifact_digests_json + OR NEW.published_object_proofs_json IS DISTINCT FROM OLD.published_object_proofs_json + OR NEW.candidate_snapshot_version_id IS DISTINCT FROM OLD.candidate_snapshot_version_id + OR NEW.candidate_public_base_url IS DISTINCT FROM OLD.candidate_public_base_url + OR NEW.selected_candidate_version_id IS DISTINCT FROM OLD.selected_candidate_version_id + OR NEW.selected_candidate_request_digest IS DISTINCT FROM OLD.selected_candidate_request_digest + OR NEW.exported_manifest_asset_keys_json IS DISTINCT FROM OLD.exported_manifest_asset_keys_json + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index 0dc3cd7287..7bf87d3332 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -12,7 +12,9 @@ import net.firedevops.firemud.gamedesign.draft.IsolatedAssetSourceOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.flywaydb.core.Flyway; @@ -404,6 +406,178 @@ void retainedPreV50CandidateWithoutOriginAllowsLifecycleUpdateButCannotBeBackfil .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); } + @Test + void sourceHistoryIndexesLeadWithNonNullAssetId() { + Fixture fixture = fixture(); + for (String table : + new String[] { + "game_design_asset_source_revision", "game_design_branding_source_revision" + }) { + var index = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT i.indisvalid, i.indisready, pg_get_indexdef(i.indexrelid, 1, true) " + + "AS first_column, pg_get_expr(i.indpred, i.indrelid) AS predicate " + + "FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid " + + "JOIN pg_namespace n ON n.oid = c.relnamespace " + + "WHERE n.nspname = ? AND c.relname = ? " + + "AND i.indrelid = to_regclass(?)", + fixture.schema, + "idx_" + table + "_asset_id", + fixture.schema + "." + table), + "source history index was not installed"); + assertThat(index.get("indisvalid", Boolean.class)).isTrue(); + assertThat(index.get("indisready", Boolean.class)).isTrue(); + assertThat(index.get("first_column", String.class)).isEqualTo("asset_id"); + assertThat(index.get("predicate", String.class)).isEqualTo("(asset_id IS NOT NULL)"); + } + } + + @Test + void selectedCandidateLifecycleWorkflowCanChangeWhileOriginalEvidenceStaysImmutable() { + Fixture fixture = fixture(); + insertSelectedCandidate(fixture); + bindSelectedCandidate(fixture, "original-export-workflow"); + var originalEvidence = + fixture.dsl.fetchOne( + "SELECT * FROM version_asset_export_candidate WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId); + VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(fixture.dsl); + var artifact = + repository.findByTenantIdAndVersionId(fixture.tenantId, fixture.versionId).orElseThrow(); + artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); + artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setLastWorkflowId("later-tombstone-workflow"); + + var saved = repository.save(artifact); + assertThat(saved.getArtifactState()).isEqualTo(VersionAssetArtifactState.TOMBSTONED); + assertThat(saved.getStateEpoch()).isEqualTo(2); + assertThat(saved.getLastWorkflowId()).isEqualTo("later-tombstone-workflow"); + var binding = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT selected_candidate_version_id, selected_candidate_request_digest " + + "FROM version_asset_artifact WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId), + "selected artifact binding readback returned no row"); + assertThat(binding.get("selected_candidate_version_id", Long.class)) + .isEqualTo(fixture.versionId); + assertThat(binding.get("selected_candidate_request_digest", String.class)) + .isEqualTo(sha256(SOURCE_BYTES).substring(7)); + assertThat( + fixture.dsl.fetchOne( + "SELECT * FROM version_asset_export_candidate " + + "WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) + .isEqualTo(originalEvidence); + for (String assignment : + new String[] { + "selected_candidate_request_digest = '" + "0".repeat(64) + "'", + "selected_candidate_version_id = NULL", + "manifest_hash = 'sha256:" + "0".repeat(64) + "'", + "published_object_proofs_json = '[]'" + }) { + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET " + + assignment + + " WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); + } + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM version_asset_artifact WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED"); + } + + @Test + void selectedCandidateRequiresOriginalWorkflowOnInsertAndFirstEvidenceUpdate() { + Fixture fixture = fixture(); + insertSelectedCandidate(fixture); + assertThatThrownBy(() -> bindSelectedCandidate(fixture, "unrelated-workflow")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT"); + insertArtifactWithoutCandidate(fixture); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET manifest_hash = ?, " + + "manifest_schema_version = 1, artifact_digests_json = '[]', " + + "published_object_proofs_json = ?, selected_candidate_version_id = ?, " + + "selected_candidate_request_digest = ?, " + + "exported_manifest_asset_keys_json = '[]', last_workflow_id = ? " + + "WHERE tenant_id = ? AND version_id = ?", + sha256(SOURCE_BYTES), + selectedManifestProof(), + fixture.versionId, + sha256(SOURCE_BYTES).substring(7), + "unrelated-workflow", + fixture.tenantId, + fixture.versionId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT"); + } + + private static void insertSelectedCandidate(Fixture fixture) { + fixture.dsl.execute( + "INSERT INTO version_asset_export_candidate " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, " + + "expected_version_state_epoch, workflow_id, request_digest, request_preimage, " + + "operation_digest, selected_commit_digest, inventory_schema, inventory_digest, " + + "inventory_bytes, manifest_schema_version, manifest_hash, manifest_bytes, " + + "artifact_digests_json, required_usage_keys_json) " + + "SELECT tenant_id, id, canonical_tenant_id, canonical_version_id, " + + "version_state_epoch, 'original-export-workflow', ?, ?, ?, ?, " + + "'game-design-selected-draft-asset-inventory/v1', ?, ?, 1, ?, ?, '[]', '[]' " + + "FROM version WHERE tenant_id = ? AND id = ?", + sha256(SOURCE_BYTES).substring(7), + SOURCE_BYTES, + sha256(SOURCE_BYTES), + sha256(SOURCE_BYTES), + sha256(SOURCE_BYTES), + SOURCE_BYTES, + sha256(SOURCE_BYTES), + SOURCE_BYTES, + fixture.tenantId, + fixture.versionId); + } + + private static void bindSelectedCandidate(Fixture fixture, String workflowId) { + fixture.dsl.execute( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, artifact_state, state_epoch, exported_version_number, " + + "manifest_hash, manifest_schema_version, artifact_digests_json, " + + "published_object_proofs_json, selected_candidate_version_id, " + + "selected_candidate_request_digest, exported_manifest_asset_keys_json, " + + "last_workflow_id) VALUES (?, ?, 'FAILED', 1, 1, ?, 1, '[]', ?, ?, ?, '[]', ?)", + fixture.tenantId, + fixture.versionId, + sha256(SOURCE_BYTES), + selectedManifestProof(), + fixture.versionId, + sha256(SOURCE_BYTES).substring(7), + workflowId); + } + + private static String selectedManifestProof() { + return "[{\"immutableObjectKey\":\"manifests/sha256/" + + sha256(SOURCE_BYTES).substring(7) + + "\",\"contentDigest\":\"" + + sha256(SOURCE_BYTES) + + "\"}]"; + } + private Fixture fixture() { return fixture(null, SOURCE_BYTES); } From 540fa37438615d7995552c08a5914545a3055d17 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:02:44 +1300 Subject: [PATCH 9/9] Fence retained asset references against stale snapshot writers --- .../game-design-service/asset-storage.md | 4 +- ...ame-authoring-publishing-and-activation.md | 10 +- ...sset_source_first_reference_mvcc_fence.sql | 33 +++ ...meDesignSourcePostgresIntegrationTest.java | 238 ++++++++++++++++++ 4 files changed, 280 insertions(+), 5 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V1030__asset_source_first_reference_mvcc_fence.sql diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 02cc4453a6..cb60525795 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,11 +6,11 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without frozen snapshot references may still be updated. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. `version_asset` rows are written only by `ordinary_asset_snapshot_projection` from synchronized ordinary asset snapshots; the direct `associateDraftAsset` method fails closed. The ordinary source-owner path and synchronized projection have controlled-input local PostgreSQL proof, while production authoring ingress remains unavailable; exports use only the exact projected set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. While a frozen export item references a source row, V37 database triggers reject changes to its identity, tenant, file name, content type, or bytes, and reject deletion or truncation. Draft source rows without retained references may still be updated. Ordinary and branding source history additionally protects bytes from its first reference: that write creates a same-transaction asset-row version without changing values, preventing writers with a pre-reference snapshot from bypassing the history guard. Controlled two-connection PostgreSQL evidence is recorded in the [receiving proof](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. `version_asset` rows are written only by `ordinary_asset_snapshot_projection` from synchronized ordinary asset snapshots; the direct `associateDraftAsset` method fails closed. The ordinary source-owner path and synchronized projection have controlled-input local PostgreSQL proof, while production authoring ingress remains unavailable; exports use only the exact projected set and do not fall back to all tenant assets. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. - **Current upload admission gap:** `GameAssetServiceImpl` now returns a structured owner-proof refusal before accessing `MultipartFile` or the repository because Account commit-bound authority is not wired. This deny-only containment does not implement the Account gate or make the Gateway-exposed route readiness-approved; it does not delete or rewrite previously accepted `game_assets` rows. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. - **Hosted-content gate gap:** Current publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route forwards `/api/design/assets` (after `StripPrefix=2`) to `POST /assets`, where the service refuses before file access or persistence. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable per-version source snapshot and export candidate preserve the selected rows and exact content-addressed object-key/digest evidence; the object writer verifies exact readback. Published repair independently reads the candidate and matches its manifest, artifact digests, and object keys to the release attestation before any object write. This does not implement the target global publication/purge fence or private candidate isolation; source identity and payload fields are database-protected while frozen snapshots reference them, and physical object-store proof remains unavailable. -- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. State-changing `VersionService.compareAndSetVersionState` requests now fail closed before a Version write; other Version writes still update by ID without a Version epoch predicate or affected-row check. Physical database execution, rollback, and concurrent-CAS proof for artifact writes are unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and that database proof. +- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. A focused PostgreSQL case proves a later lifecycle workflow can persist its artifact state and epoch while preserving the original selected-candidate evidence; see the [receiving proof](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). State-changing `VersionService.compareAndSetVersionState` requests fail closed before a Version write; other Version writes still update by ID without a Version epoch predicate or affected-row check. Physical rollback and concurrent-CAS proof remain unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and those proofs. - The isolated run-owned launch receipt carries the actual committed release-bundle, artifact-state, and version-state projections together with the resolved persisted launch descriptor. This is fixture launch provenance only and grants no production read, asset-byte, object-store, or purge authority. Its bounded wire shape and producer/consumer ordering are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. - **Current purge finalization:** `AssetExportServiceImpl.deleteExportedAssets` rejects every prefix-based delete with `CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED` before accessing S3. `FinalizePurgeVersionAssets` still reaches this fail-closed boundary after its current lifecycle checks; it does not delete objects. Exported objects are content-addressed and may be shared, so the persisted `exported_version_number` selection cannot establish safe deletion. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below; physical purge proof remains incomplete. 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 620fe00cf3..4244057987 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its owned boundary comprises 66 Game Design/shared-contract/caller/proof paths, eleven preserved Logging receiving paths and one process-observation document, for 78 unique receiving paths. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. The published CLI2 source `371f0dcedc75690aadb7cb267b4a19ddbc8c16ff` passed its exact-head Validation, CodeQL, License and Security gates. Current review fixes require new published-source CI; Hosted/CLI review and rebuilt packaged receiver proof remain separate gates. Earlier results retain their original source attribution. +The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its coherent boundary includes Game Design/shared-contract/caller/proof paths, preserved Logging receiving paths, and bounded CI/process repairs. The PR’s generated scope section records its current path count. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. The published CLI2 source `371f0dcedc75690aadb7cb267b4a19ddbc8c16ff` passed its exact-head Validation, CodeQL, License and Security gates. Current review fixes require new published-source CI; Hosted/CLI review and rebuilt packaged receiver proof remain separate gates. Earlier results retain their original source attribution. ### Coherent owner receiving prerequisite @@ -18,7 +18,11 @@ The accepted CLI2 corrections passed the consolidated local Common/GDS gate in 4 The CLI3/first Hosted fix batch passed Game Design formatting, actual jOOQ generation, compilation, static checks and all 503 unit and 129 physical PostgreSQL cases with zero failures, errors or skips. The four-minute-five-second combined invocation failed only two newly added tracker link targets; those targets were corrected and the final documentation gate was run separately. The new physical case preserves enabled ordinary-source immutability guards: byte, content-type, file-name and null writes are rejected with SQLSTATE `23514`, and each subsequent synchronized read returns the same complete snapshot. Normal readback computes digest and size in PostgreSQL rather than transferring every source payload to Java; locked source-write qualification remains unchanged. Fresh and retained-history upgrade proof installs 86 migration entries through V1026 while preserving predecessor rows and checksums. The parent-pinned migration checker passes twelve sets and 295 versioned files. Common's 482 cases and Logging's 272 unit/25 integration cases retain their preceding execution attribution; this Game Design gate did not rerun them. These results do not establish genuine producer authority or rebuilt packaged receiver activation. -Historical earlier-parent result: the complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passed formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executed 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executed all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history had 62 entries; upgrade and fresh histories had 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases retain their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verified their unchanged inputs as up-to-date rather than relabeling them fresh. This 63-path/127-case result is historical for that parent and is not the current 66-path/503-unit/129-PostgreSQL receiver proof. +The CLI5 postimage `7d007482de547fc4e3f02bb75842a5d83558c0a7` passed its locked Game Design gate in 4m38s, freshly executing 503 unit and 132 physical PostgreSQL cases with zero failures, errors or skips. Forward V1028 adds asset-leading history indexes and restricts selected-candidate workflow equivalence to initial binding while preserving frozen evidence. New physical cases verify both indexes, a real artifact repository lifecycle workflow/epoch update, immutable evidence and deletion refusal, and incorrect initial binding refusal. The parent-pinned migration checker passed twelve sets/296 files; formatting, compilation, jOOQ generation, static and documentation checks passed. These bounded lifecycle and storage results do not establish lifecycle authorization, concurrent artifact CAS, production branding ingress or object-store deletion. + +The CLI6 repair adds forward V1030, leaving earlier migration bytes unchanged. Ordinary and branding first-reference writes create a same-transaction asset-row version without changing values, so a stale `REPEATABLE READ` byte writer cannot miss committed source history and mutate retained bytes. Four controlled two-connection PostgreSQL cases reproduced the violation before the repair, then passed with SQLSTATE `40001`, exact retained bytes/content type and deletion refusal. Ordinary uses the existing isolated owner producer; branding uses controlled SQL with the installed genesis/coordinator/source guards active. This is schema/source-history proof, not production branding ingress. The locked broader postimage gate passed in 4m15s, freshly executing 503 unit and 136 physical PostgreSQL cases with zero failures, errors or skips; jOOQ was up-to-date from the focused run. Formatting, compilation, static checks and documentation passed, and the parent-pinned checker passed twelve migration sets/297 files. Current-source CI, rebuilt packaged runtime and genuine producer authority remain separate. + +Historical earlier-parent result: the complete composition gate on parent `4e45c706c79a898d82f6c6902ba8bec0f611f2d5` passed formatting, full service static checks, metadata generation, immutable-parent migration preservation, exported Game Session fixture compilation and documentation checks. Logging freshly executed 272 unit cases and 25 PostgreSQL/service integration cases with zero failures, errors or skips. The subsequent explicitly rerun Game Design task physically executed all 127 PostgreSQL cases with zero failures, errors or skips, including current source UPSERT/inheritance/DELETE, synchronized projection, publication and terminal readback, and retained publication/review-v1 upgrades. Actual installed-parent history had 62 entries; upgrade and fresh histories had 84. Shared Core's 481 cases, Test Support's 55 cases and Game Design's 502 unit cases retain their earlier fresh execution attribution on `f3afc0505de766ac2ae2ac6b90d5814ab22d3ef9`; the complete composition gate verified their unchanged inputs as up-to-date rather than relabeling them fresh. This 63-path/127-case result is historical for that parent and does not replace the later receiver proof attributed above. Parent `68ee9a6094181d233988c47588a66dceb7dbe6ea` changed only two Entity selected-assignment source/unit postimages from `4e45c706c79a898d82f6c6902ba8bec0f611f2d5`. Parent `4925747b7eca6a4b5c9e043479492813bf6a6c1e` adds the accepted Entity legacy numeric-read/holder isolation guards and owning tracker status; all Account, Common, Game Design, Logging and migration inputs were byte-identical at that parent. Its separate full Entity proof covers 237 unit and 27 physical PostgreSQL cases without failures, errors or skips, including retained legacy behavior and exact canonical owner methods. Generated TCP consumer compilation passed freshly; its full 192 unit and seven integration cases retain their earlier execution attribution. Account's 18 physical PostgreSQL cases keep their qualified unchanged-input attribution. The previous preparation parent `d7c8f84fa947644a651304205803c3919c81684e` changed only the review controller and its tests from `4925747`; its owner runtime and migration byte-identity statement applies to that parent only. The newer parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` includes new Account SQL, so the earlier Account byte-identity statement does not apply to the latest parent. The receiver carries each parent proof with its original attribution, while exact-head CI and review remain separate. These are parent proofs, not receiver execution. Logging preserves the original authorization tuple through exact durable readback and a one-time owner handoff. Eight loopback mTLS cases use a synthetic Account handler, and controlled coordinator doubles do not establish genuine Account issuance. Superseded [#3190](https://github.com/benhook1013/FireMUD/pull/3190) and [#3193](https://github.com/benhook1013/FireMUD/pull/3193) are closed under explicit authorization, with their branches, worktrees and proof retained. @@ -221,7 +225,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Inventory/equipment was a documentation-only authority decision with no runtime behavior change; its recorded proof is `./gradlew linkCheck lintMarkdown`. - Settings schema/reference generation and verification are available through `./gradlew updatePlatformSettingsDocs` and `./gradlew verifyPlatformSettingsDocs`; persistence, resolution, cache/invalidation, generation, and surfaced-domain coverage are complete at their recorded boundaries. - The broader domain's aggregate documentation checkpoint completed on 2026-08-14 Pacific/Auckland (2026-08-13 UTC): `./gradlew linkCheck lintMarkdown` checked 4,574 links (4,536 OK, 0 errors, 38 excluded) and 454 Markdown files with 0 issues; `bash dev-tools/tests/architecture-doc-contracts.sh` also passed separately (184 tests passed). -- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering, and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Current implementation has version-asset mappings, a durable export snapshot, candidate evidence, and an exact-bundle published repair check, but no production Draft mapping caller; full-version ingress therefore remains fail-closed. Purge still mints a random workflow ID; Version state lacks database CAS; exact committed-bundle recovery and physical database/object-store proof remain incomplete. Artifact-row updates have an epoch predicate and affected-row check, but their database execution proof is unavailable. +- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering, and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Current implementation has version-asset mappings, a durable export snapshot, candidate evidence, and an exact-bundle published repair check, but no production Draft mapping caller; full-version ingress therefore remains fail-closed. Purge still mints a random workflow ID; Version state lacks database CAS; exact committed-bundle recovery and physical database/object-store proof remain incomplete. Artifact-row updates have an epoch predicate and affected-row check; a focused selected-candidate lifecycle update now has physical PostgreSQL proof, while concurrent CAS and rollback proof remain unavailable. - The current Packet 5 documentation-only validation record is maintained in the canonical [design capability allocation](../design-alignment/design-capability-allocation.md#validation-and-proof-references); that ledger entry proves only the Packet 5 documentation/allocation checkpoint. It neither claims runtime proof for that parcel nor weakens the separately listed implementation proof and commands in this tracker. ## Active Gaps diff --git a/services/game-design-service/src/main/resources/db/migration/V1030__asset_source_first_reference_mvcc_fence.sql b/services/game-design-service/src/main/resources/db/migration/V1030__asset_source_first_reference_mvcc_fence.sql new file mode 100644 index 0000000000..b2161a7311 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1030__asset_source_first_reference_mvcc_fence.sql @@ -0,0 +1,33 @@ +-- A row lock alone does not invalidate a pre-reference REPEATABLE READ snapshot. +-- Create a new asset row version in the same transaction that first retains its bytes. +-- All values remain identical, so existing identity and retained-byte guards still apply. +-- [jooq ignore start] +CREATE FUNCTION fence_asset_source_reference_mvcc() RETURNS TRIGGER AS $$ +BEGIN + IF NEW.operation_kind = 'UPSERT' THEN + UPDATE game_assets asset + SET data = asset.data + FROM version owner + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id + AND asset.id = NEW.asset_id + AND asset.tenant_id = owner.tenant_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'asset source MVCC fence requires exact tenant-qualified asset row' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- PostgreSQL orders same-kind triggers by name: each fence follows its canonical revision guard, +-- which has already admitted and locked the exact asset and verified its immutable evidence. +CREATE TRIGGER ordinary_asset_revision_mvcc_fence + BEFORE INSERT ON game_design_asset_source_revision + FOR EACH ROW EXECUTE FUNCTION fence_asset_source_reference_mvcc(); + +CREATE TRIGGER branding_asset_revision_mvcc_fence + BEFORE INSERT ON game_design_branding_source_revision + FOR EACH ROW EXECUTE FUNCTION fence_asset_source_reference_mvcc(); +-- [jooq ignore stop] 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 index 97454f83d5..b6090e4809 100644 --- 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 @@ -3,7 +3,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; import java.util.HexFormat; import java.util.List; import java.util.Map; @@ -16,6 +21,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; @@ -50,6 +56,218 @@ class GameDesignSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void firstReferenceRejectsStaleOrdinaryByteUpdate() throws Exception { + assertFirstReferenceRejectsStaleUpdate(false, false); + } + + @Test + void firstReferenceRejectsStaleOrdinaryMetadataUpdate() throws Exception { + assertFirstReferenceRejectsStaleUpdate(false, true); + } + + @Test + void firstReferenceRejectsStaleBrandingByteUpdate() throws Exception { + assertFirstReferenceRejectsStaleUpdate(true, false); + } + + @Test + void firstReferenceRejectsStaleBrandingMetadataUpdate() throws Exception { + assertFirstReferenceRejectsStaleUpdate(true, true); + } + + private static void assertFirstReferenceRejectsStaleUpdate(boolean branding, boolean metadata) + throws Exception { + Fixture fixture = fixture(branding); + byte[] bytes = {0, 1, (byte) 0xff}; + long assetId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " + + "VALUES (?, 'logo.bin', 'application/octet-stream', ?) RETURNING id", + fixture.target().gameDesignVersionTenantKey(), + bytes) + .get(0, Long.class); + // Draft bytes are still mutable before the first source reference. + assertThat( + fixture.dsl().execute("UPDATE game_assets SET data = ? WHERE id = ?", bytes, assetId)) + .isEqualTo(1); + String history = + branding ? "game_design_branding_source_revision" : "game_design_asset_source_revision"; + try (Connection stale = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + stale.setSchema(fixture.schema()); + stale.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + stale.setAutoCommit(false); + DSLContext staleDsl = DSL.using(stale, SQLDialect.POSTGRES); + assertThat(staleDsl.fetchCount(DSL.table(history))).isZero(); + assertThat( + staleDsl + .fetchSingle("SELECT data FROM game_assets WHERE id = ?", assetId) + .get(0, byte[].class)) + .containsExactly(bytes); + if (branding) { + fixture.tx( + () -> { + applyBrandingFirstReference(fixture, assetId); + return null; + }); + } else { + fixture.tx( + () -> + IsolatedAssetSourceOwnerSetup.upsert( + fixture.dsl(), fixture.target(), assetId, "logo.bin")); + } + assertThat(fixture.dsl().fetchCount(DSL.table(history))).isEqualTo(1); + // A still sees the pre-reference history, so a row version fence must reject its write. + assertThat(staleDsl.fetchCount(DSL.table(history))).isZero(); + assertThatThrownBy( + () -> + staleDsl.execute( + metadata + ? "UPDATE game_assets SET content_type = ? WHERE id = ?" + : "UPDATE game_assets SET data = ? WHERE id = ?", + metadata ? "image/png" : new byte[] {9}, + assetId)) + .rootCause() + .isInstanceOfSatisfying( + PSQLException.class, failure -> assertThat(failure.getSQLState()).isEqualTo("40001")); + stale.rollback(); + } + var retained = + fixture + .dsl() + .fetchSingle("SELECT data, content_type FROM game_assets WHERE id = ?", assetId); + assertThat(retained.get("data", byte[].class)).containsExactly(bytes); + assertThat(retained.get("content_type", String.class)).isEqualTo("application/octet-stream"); + assertThatThrownBy(() -> fixture.dsl().execute("DELETE FROM game_assets WHERE id = ?", assetId)) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining("source bytes are immutable from source history"); + } + + /** Controlled branding schema producer: all installed coordinator/source guards remain active. */ + private static void applyBrandingFirstReference(Fixture fixture, long assetId) { + var target = fixture.target(); + var genesis = fixture.sources().readGenesis(target).orElseThrow(); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis:" + genesis.policy().receiptId(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + BrandingSource.upsertPayload( + Long.toString(assetId), + "logo.bin", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + BrandingSource.SCOPE, + target.canonicalVersionId().toString(), + BrandingSource.SCOPE, + BrandingSource.SCOPE_ID, + "0"))); + start(fixture, binding); + fixture + .dsl() + .execute( + "INSERT INTO game_design_branding_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, " + + "revision_order, operation_kind, usage_key, role, asset_id, requiredness, content_type, content_digest, byte_size) " + + "SELECT ?, ?, ?, ?, ?, 0, 'UPSERT', file_name, 'LOGO', id, 'REQUIRED', content_type, " + + "'sha256:' || encode(sha256(data), 'hex'), octet_length(data) FROM game_assets WHERE id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.revisions().getFirst().revisionId(), + assetId); + String snapshot = + fixture + .dsl() + .fetchSingle( + "SELECT jsonb_build_object('schema', 'game-design-branding-asset-source-snapshot/v1', " + + "'bindingJson', c.binding_json, 'bindingDigest', c.input_digest, 'genesisReceiptId', g.receipt_id::TEXT, " + + "'inheritedCommitId', '', 'sourceEpoch', '1', 'items', jsonb_build_array(branding_asset_revision_item(r)), " + + "'roles', jsonb_build_object('RESOURCE', 'EMPTY', 'LOGO', 'PRESENT', 'FAVICON', 'EMPTY', 'THEME', 'EMPTY'))::TEXT " + + "FROM game_design_branding_source_revision r " + + "JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "JOIN game_design_branding_source_genesis g USING (canonical_tenant_id, canonical_version_id) WHERE r.commit_id = ?", + binding.commitId()) + .get(0, String.class); + byte[] application = + frames( + "game-design-branding-asset-source-application/v1".getBytes(StandardCharsets.UTF_8), + "0".getBytes(StandardCharsets.UTF_8), + snapshot.getBytes(StandardCharsets.UTF_8)); + fixture + .dsl() + .execute( + "INSERT INTO game_design_branding_source_application " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, '0', ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot, + application); + fixture + .dsl() + .execute( + "UPDATE game_design_branding_source_head SET source_epoch = '1', applied_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId()); + byte[] components = + frames( + "game-design-control-plane-sibling-components/v1".getBytes(StandardCharsets.UTF_8), + "BRANDING".getBytes(StandardCharsets.UTF_8), + application); + byte[] result = + frames( + "game-design-control-plane-ordinary-source-application/v1" + .getBytes(StandardCharsets.UTF_8), + binding.canonicalJson().getBytes(StandardCharsets.UTF_8), + components); + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "isolated-branding-first-reference", + result, + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + BrandingSource.SCOPE, + target.canonicalVersionId().toString(), + BrandingSource.SCOPE, + BrandingSource.SCOPE_ID, + "0", + "1")))); + } + + private static byte[] frames(byte[]... values) { + var result = new ByteArrayOutputStream(); + for (byte[] value : values) { + result.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + result.writeBytes(value); + } + return result.toByteArray(); + } + @Test void ordinaryAssetSourceProjectsInheritedAndDeletedReferencesThroughCoordinatorFence() throws Exception { @@ -730,6 +948,10 @@ private static String command(String id, String alias) { } private static Fixture fixture() { + return fixture(false); + } + + private static Fixture fixture(boolean branding) { String schema = "gd_combined_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource( @@ -760,6 +982,20 @@ private static Fixture fixture() { version.setTenantId(game.getTenantId()); version.setVersionNumber(1); version = new VersionRepository(dsl).save(version); + if (branding) { + dsl.execute( + "INSERT INTO game_design_branding_source_genesis " + + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json, roles_json) " + + "SELECT canonical_tenant_id, canonical_version_id, version_id, ?, creation_transaction_id, target_json, " + + "'{\"RESOURCE\":\"EMPTY\",\"LOGO\":\"EMPTY\",\"FAVICON\":\"EMPTY\",\"THEME\":\"EMPTY\"}' " + + "FROM game_design_asset_source_genesis WHERE version_id = ?", + UUID.randomUUID(), + version.getId()); + dsl.execute( + "INSERT INTO game_design_branding_source_head (canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) " + + "SELECT canonical_tenant_id, canonical_version_id, '0', receipt_id FROM game_design_branding_source_genesis WHERE version_id = ?", + version.getId()); + } return new TargetProof( version.getCanonicalTenantId(), version.getCanonicalVersionId(), @@ -770,6 +1006,7 @@ private static Fixture fixture() { version.getIdentitySourceProvenanceKind()); }); return new Fixture( + schema, dsl, write, target, @@ -778,6 +1015,7 @@ private static Fixture fixture() { } private record Fixture( + String schema, DSLContext dsl, TransactionTemplate write, TargetProof target,