From 78223b2e7e14124a27bc94c52f21f961c406a58e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:33:16 +1300 Subject: [PATCH 1/7] Add guarded World topology and immutable graph owner storage --- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 9 +- .../world-runtime-and-movement.md | 10 +- .../entity/WorldEntitySpawnBinding.java | 4 + .../WorldEntitySpawnBindingRepository.java | 18 + .../WorldDraftDesignDigestServiceImpl.java | 232 ++-- .../tenant/WorldAuthoredGraph.java | 471 ++++++++ .../tenant/WorldAuthoredGraphReader.java | 325 ++++++ .../tenant/WorldAuthoredGraphSnapshot.java | 208 ++++ .../WorldAuthoredGraphSnapshotCapture.java | 329 ++++++ .../WorldAuthoredGraphSnapshotRepository.java | 599 ++++++++++ .../tenant/WorldCanonicalAuthoredGraph.java | 98 ++ .../WorldCanonicalAuthoredGraphReader.java | 176 +++ .../tenant/WorldCanonicalFrozenTopology.java | 124 ++ ...orldCanonicalFrozenTopologyRepository.java | 288 +++++ .../WorldCanonicalFrozenTopologyService.java | 43 + .../WorldDraftTopologyCommitEvidence.java | 51 + .../tenant/WorldDraftTopologyCommitPlan.java | 362 ++++++ .../WorldDraftTopologyCommitRepository.java | 617 ++++++++++ .../tenant/WorldDraftTopologyInputGraph.java | 81 ++ .../V1003__world_authored_graph_snapshot.sql | 264 +++++ ...04__world_guarded_region_draft_commits.sql | 392 +++++++ ...5__world_guarded_uuid_topology_commits.sql | 490 ++++++++ ...V1006__world_canonical_frozen_topology.sql | 96 ++ ..._restore_stable_legacy_update_fastpath.sql | 30 + .../V1007__world_digest_schema3_capture.sql | 39 + ...edGraphCapturePostgresIntegrationTest.java | 1034 +++++++++++++++++ ...WorldDraftDesignDigestServiceImplTest.java | 35 +- .../WorldGuardedAuthoredTopologyPlanTest.java | 129 ++ 29 files changed, 6460 insertions(+), 96 deletions(-) create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index d52e8ebb65..45ab4d5d03 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. An unpublished component-owner candidate now includes graph capture and the ordinary schema-3 digest writer; its checkpoint producer and focused proof remain incomplete, as recorded in the tracker. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index a0a97a2368..2c6b9b55c0 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). An unpublished guarded graph/capture candidate includes the ordinary schema-3 digest writer; its exact checkpoint producer and focused proof are incomplete and are recorded in the tracker. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -26,9 +26,9 @@ A fresh intake completes its authenticated Game Design source read before openin World Management retains exact authored-source evidence as owner-local source data. The intake receipt binds the target namespace, canonical tenant UUID, world selector, source operation and evidence digest, and immutable request/receipt identities. World reserves numeric tenant keys already present in its data and prevents those legacy keys from being reused for a canonical authored tenant association; it does not reinterpret or migrate existing `V1`–`V23` rows into the new UUID identity. -The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. +The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. The separate guarded graph/capture candidate retains component evidence under the same owner and uses schema 3; this does not supply Account authorization, synchronized APPLIED or a released snapshot. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. -The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. Focused physical PostgreSQL and mTLS proof for the tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). +The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The separate V1003 graph-snapshot migration uses that installed publication-owner association without duplicating its V27.1 binding clauses. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. The guarded owner stage adds unchanged V1003–V1007 donor migrations and forward V1007.1 legacy-concurrency repair above the installed Saga frontier V1002. Its graph/capture storage remains representation evidence; current frozen producer and proof status are recorded separately in the tracker. Focused physical PostgreSQL and mTLS proof for the tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: @@ -196,7 +196,8 @@ Implementation Notes: - stable table ordering; - primary-key ordering within each table; - deterministic encoding for included semantic fields. -- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Null string values are canonicalized as empty strings before hashing. The current World digest schema version is `2` because scoped generation-rule metadata is now hashed. +- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Null string values are canonicalized as empty strings before hashing. The current ordinary World digest schema version is `3`; scoped generation-rule metadata and tagged Entity spawn references are included in its deterministic projection. +- Spawn references use an explicit tagged representation: retained positive numeric private keys remain numeric evidence; canonical references retain exact non-nil tenant, Version and Entity template UUIDs. Mixed or partial representations are rejected. - `digestSchemaVersion` must increment whenever included tables, field-selection rules, or canonical serialization semantics change. Publish gating fails closed if World Management cannot attest a digest consistent with this manifest. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 9d11840f0a..b34797bc5c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,17 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +### Guarded graph capture and frozen owner stage + +The World owner stage carries immutable donor migrations V1003–V1007 for guarded six-family topology, authored/canonical graph storage and schema-3 capture. The ordinary digest writer now emits schema 3 with tagged numeric-versus-canonical Entity references through its installed interface. The installed 31 World plus three Saga artifacts remain unchanged. New V1007.1 restores the installed V27.2 stable same-tenant legacy UPDATE fastpath after V1004; later donor guard replacements must preserve that same invariant through their own forward repairs. No shared/protobuf or Game Design/Game Session fixture contracts are introduced, and the existing private fixture bootstrap is unchanged. + +The stage is component-only: PURE_UNVERIFIED input, STORED_PERMISSION_UNVERIFIED topology and CAPTURED_UNVERIFIED capture do not establish Account authorization, APPLIED synchronization, selected inbound closure, release, runtime preparation, activation or operational-region authority. The ordinary digest retains its synthetic `version:` token. Live canonical frozen capture remains unqualified: it requires the original complete commit UUID, while the authenticated Game Design complete-commit/head and expected World revision-vector producer is absent. Individual APPLIED V19 rows lack complete-commit and head-order evidence; stored topology cannot supply it. The frozen request keeps exact checkpoint equality and fails closed without this producer. Source/Version upstream test evidence is explicitly controlled. + +Focused definitions cover strict typed input/digest behavior, physical default-order parent34→stage40 preservation with original column bytes and xmin, independently updatable legacy rows, real guarded six-family store/replay, naked-write refusal and missing-checkpoint denial. The complete World service gate passed on parent `310532f10b8aa90d50e455e5ebc61a9c7e0b1cc2` with 273 fresh unit and 63 fresh physical PostgreSQL integration tests, zero failures/errors/skips, static checks and Markdown/link validation. This includes real guarded store/replay, source/version and installed34→stage40 retention plus legacy update concurrency. A follow-up whole service gate on parent `540fa37438615d7995552c08a5914545a3055d17` passed with 64 fresh PostgreSQL integrations and the same 273 unit results reused from the earlier gate, plus full static and documentation checks. It physically verifies direct current capture refusal without V19 history and schema-2 snapshot repository retention across V1006→V1007/V1007.1 with every original field, graph byte and xmin unchanged. That retention test uses explicitly controlled predecessor checkpoint/content metadata and real Source/Version/fence/snapshot repositories; it establishes storage retention, never the preceding capture producer, Account authorization or complete APPLIED synchronization. The normal carry to `55c23f79f47827f2926f8277ad894eada746def2` changed seven CI/Entity/tool/documentation paths and preserved all World/Common/protobuf postimages. Positive live frozen capture/readback and packaged fresh/restart runtime remain unrun. Earlier carrier proof does not qualify this stage. All genuine protected handoffs and Unit 1B holds remain open. + ### Authored World Source Retention Status -The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. That historical source-retention proof excluded graph capture and used digest schema 2; the separate guarded owner stage above introduces graph/capture storage and the schema-3 writer with its own qualification boundary. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. The earlier clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` remains attributable to that candidate: it reported 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in that gate, including the same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. At `42296c26c91459c229a6822c5a6fc81c8b0da4d1`, the focused World proof reports 263 unit cases, reused unchanged from the freshly executed unit suite at `c62de7bf127908cece54e6d97f4565b3147be9be`, including its SQL-state classification regression and 61 fresh PostgreSQL integration cases, with zero failures, errors, or skips. The PostgreSQL cases include timeout rollback, exact retry, and tighter-limit reset coverage. The clean World formatter/check/linkCheck run reported 10,822 links checked and the Markdown lint reported 550 files with zero issues. These results are focused local proof only; they do not establish a new combined Core/Game Design/World gate, full CI, external database application, runtime registration, or activation. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java index de672ba3bb..09805f65ac 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.entity; +import java.util.UUID; import lombok.Data; @Data @@ -10,6 +11,9 @@ public class WorldEntitySpawnBinding { private Room room; private String entityTemplateType; private Long entityTemplateId; + private UUID entityCanonicalTenantId; + private UUID entityCanonicalVersionId; + private UUID entityCanonicalTemplateId; private int spawnCount = 1; private int respawnDelaySeconds; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java index c62b8cbc3f..fbccb4f069 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java @@ -85,6 +85,15 @@ public WorldEntitySpawnBinding save(WorldEntitySpawnBinding entity) { .set(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID, entity.getRoom().getId()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE, entity.getEntityTemplateType()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID, entity.getEntityTemplateId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID, + entity.getEntityCanonicalTenantId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID, + entity.getEntityCanonicalVersionId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID, + entity.getEntityCanonicalTemplateId()) .set(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT, entity.getSpawnCount()) .set(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS, entity.getRespawnDelaySeconds()) .set(WORLD_ENTITY_SPAWN_BINDING.VERSION, entity.getVersion() + 1) @@ -124,6 +133,9 @@ private void populate(WorldEntitySpawnBindingRecord record, WorldEntitySpawnBind record.setRoomId(entity.getRoom().getId()); record.setEntityTemplateType(entity.getEntityTemplateType()); record.setEntityTemplateId(entity.getEntityTemplateId()); + record.setEntityCanonicalTenantId(entity.getEntityCanonicalTenantId()); + record.setEntityCanonicalVersionId(entity.getEntityCanonicalVersionId()); + record.setEntityCanonicalTemplateId(entity.getEntityCanonicalTemplateId()); record.setSpawnCount(entity.getSpawnCount()); record.setRespawnDelaySeconds(entity.getRespawnDelaySeconds()); record.setVersion(entity.getVersion()); @@ -139,6 +151,12 @@ private WorldEntitySpawnBinding toEntity(Record record) { record.get(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID))); entity.setEntityTemplateType(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE)); entity.setEntityTemplateId(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID)); + entity.setEntityCanonicalTenantId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID)); + entity.setEntityCanonicalVersionId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID)); + entity.setEntityCanonicalTemplateId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID)); Integer spawnCount = record.get(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT); entity.setSpawnCount(spawnCount == null ? 1 : spawnCount); Integer respawnDelaySeconds = record.get(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index 48306bfc76..cc77707130 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -4,8 +4,14 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -13,6 +19,7 @@ import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; import org.springframework.stereotype.Service; import tools.jackson.databind.ObjectMapper; @@ -20,8 +27,8 @@ @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Spring-managed repositories and mapper are stored internally for digesting") -public class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { - private static final int DIGEST_SCHEMA_VERSION = 2; +public final class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { + private static final int DIGEST_SCHEMA_VERSION = 3; private final RegionRepository regionRepository; private final ZoneRepository zoneRepository; @@ -45,7 +52,9 @@ public WorldDraftDesignDigestServiceImpl( this.roomExitRepository = roomExitRepository; this.generationRuleRepository = generationRuleRepository; this.worldEntitySpawnBindingRepository = worldEntitySpawnBindingRepository; - this.objectMapper = objectMapper; + Objects.requireNonNull(objectMapper, "objectMapper"); + // Schema serialization must not inherit application-wide pretty-printing or map-order options. + this.objectMapper = new ObjectMapper(); } @Override @@ -56,92 +65,88 @@ public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versi long tenantKey = RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); long versionKey = RequestIdValidation.requirePositiveLong(versionId, "versionId"); try { - String canonicalJson = - objectMapper.writeValueAsString( - Map.of( - "regions", - regionRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - region -> - Map.of( - "id", region.getId(), - "shardId", region.getShardId(), - "name", region.getName(), - "weather", value(region.getWeather()), - "generationSeed", region.getGenerationSeed(), - "generatorType", value(region.getGeneratorType()), - "generatorParams", value(region.getGeneratorParams()), - "spacingMultiplier", region.getSpacingMultiplier())) - .toList(), - "zones", - zoneRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - zone -> - Map.of( - "id", zone.getId(), - "regionId", zone.getRegion().getId(), - "name", zone.getName())) - .toList(), - "rooms", - roomRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - room -> - Map.of( - "id", room.getId(), - "zoneId", room.getZone().getId(), - "name", room.getName(), - "description", value(room.getDescription()), - "nameLocalizedVariantsJson", - value(room.getNameLocalizedVariantsJson()), - "descriptionLocalizedVariantsJson", - value(room.getDescriptionLocalizedVariantsJson()))) - .toList(), - "roomExits", - roomExitRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - roomExit -> - Map.of( - "id", roomExit.getId(), - "fromRoomId", roomExit.getFromRoom().getId(), - "toRoomId", roomExit.getToRoom().getId(), - "direction", roomExit.getDirection(), - "cost", roomExit.getCost())) - .toList(), - "generationRules", - generationRuleRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - rule -> - Map.of( - "id", rule.getId(), - "name", rule.getName(), - "scopeType", value(rule.getScopeType()), - "scopeId", value(rule.getScopeId()), - "value", value(rule.getValue()))) - .toList(), - "worldEntitySpawnBindings", - worldEntitySpawnBindingRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - binding -> - Map.of( - "id", binding.getId(), - "roomId", binding.getRoom().getId(), - "entityTemplateType", binding.getEntityTemplateType(), - "entityTemplateId", binding.getEntityTemplateId(), - "spawnCount", binding.getSpawnCount(), - "respawnDelaySeconds", binding.getRespawnDelaySeconds())) - .toList())); + Map digestInput = + tables( + "regions", + regionRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + region -> + Map.of( + "id", region.getId(), + "shardId", region.getShardId(), + "name", region.getName(), + "weather", value(region.getWeather()), + "generationSeed", region.getGenerationSeed(), + "generatorType", value(region.getGeneratorType()), + "generatorParams", value(region.getGeneratorParams()), + "spacingMultiplier", region.getSpacingMultiplier())) + .toList(), + "zones", + zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() + .map( + zone -> + Map.of( + "id", zone.getId(), + "regionId", zone.getRegion().getId(), + "name", zone.getName())) + .toList(), + "rooms", + roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() + .map( + room -> + Map.of( + "id", room.getId(), + "zoneId", room.getZone().getId(), + "name", room.getName(), + "description", value(room.getDescription()), + "nameLocalizedVariantsJson", + value(room.getNameLocalizedVariantsJson()), + "descriptionLocalizedVariantsJson", + value(room.getDescriptionLocalizedVariantsJson()))) + .toList(), + "roomExits", + roomExitRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + roomExit -> + Map.of( + "id", roomExit.getId(), + "fromRoomId", roomExit.getFromRoom().getId(), + "toRoomId", roomExit.getToRoom().getId(), + "direction", roomExit.getDirection(), + "cost", roomExit.getCost())) + .toList(), + "generationRules", + generationRuleRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + rule -> + Map.of( + "id", rule.getId(), + "name", rule.getName(), + "scopeType", value(rule.getScopeType()), + "scopeId", value(rule.getScopeId()), + "value", value(rule.getValue()))) + .toList(), + "worldEntitySpawnBindings", + worldEntitySpawnBindingRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + binding -> + Map.of( + "id", binding.getId(), + "roomId", binding.getRoom().getId(), + "entityTemplateType", binding.getEntityTemplateType(), + "entityReference", entityReference(binding), + "spawnCount", binding.getSpawnCount(), + "respawnDelaySeconds", binding.getRespawnDelaySeconds())) + .toList()); + String canonicalJson = objectMapper.writeValueAsString(digestInput); return new WorldDraftDesignDigest( tenantId, versionId, @@ -157,6 +162,55 @@ private String value(String value) { return value == null ? "" : value; } + // Top-level table order is part of the manifest, while every nested object is field-sorted. + private Map tables(Object... entries) { + Map tables = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + tables.put((String) entries[index], canonical(entries[index + 1])); + } + return tables; + } + + private Object canonical(Object value) { + if (value instanceof Map fields) { + Map sorted = new TreeMap<>(); + fields.forEach((key, item) -> sorted.put((String) key, canonical(item))); + return sorted; + } + if (value instanceof List rows) { + return rows.stream().map(this::canonical).toList(); + } + return value; + } + + private Map entityReference(WorldEntitySpawnBinding binding) { + UUID tenant = binding.getEntityCanonicalTenantId(); + UUID version = binding.getEntityCanonicalVersionId(); + UUID template = binding.getEntityCanonicalTemplateId(); + Long numeric = binding.getEntityTemplateId(); + if (numeric != null) { + if (numeric <= 0 || tenant != null || version != null || template != null) { + throw new IllegalArgumentException("spawn Entity reference is mixed or nonpositive"); + } + return Map.of("kind", "RETAINED_PRIVATE_KEY", "templateId", numeric.toString()); + } + requireNonNil(tenant); + requireNonNil(version); + requireNonNil(template); + return Map.of( + "kind", "CANONICAL_UUID", + "tenantId", tenant.toString(), + "versionId", version.toString(), + "templateId", template.toString()); + } + + private void requireNonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "spawn Entity reference must contain complete non-nil UUIDs"); + } + } + private String sha256(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java new file mode 100644 index 0000000000..8956b4f184 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java @@ -0,0 +1,471 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable World-owned value and codec for the six version-scoped authored content families. */ +public final class WorldAuthoredGraph { + private static final int SNAPSHOT_SCHEMA_VERSION = 1; + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final List> regions; + private final List> zones; + private final List> rooms; + private final List> roomExits; + private final List> generationRules; + private final List> spawnBindings; + + public WorldAuthoredGraph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + this.regions = copyRows(regions, false); + this.zones = copyRows(zones, false); + this.rooms = copyRows(rooms, false); + this.roomExits = copyRows(roomExits, false); + this.generationRules = copyRows(generationRules, false); + this.spawnBindings = copyRows(spawnBindings, false); + } + + public List> regions() { + return copyRows(regions, true); + } + + public List> zones() { + return copyRows(zones, true); + } + + public List> rooms() { + return copyRows(rooms, true); + } + + public List> roomExits() { + return copyRows(roomExits, true); + } + + public List> generationRules() { + return copyRows(generationRules, true); + } + + public List> spawnBindings() { + return copyRows(spawnBindings, true); + } + + /** + * Encodes the canonical snapshot representation using the capture component's configured mapper. + */ + public byte[] encode(ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + LinkedHashMap root = new LinkedHashMap<>(); + root.put("snapshotSchemaVersion", SNAPSHOT_SCHEMA_VERSION); + root.put("regions", regions); + root.put("zones", zones); + root.put("rooms", rooms); + root.put("roomExits", roomExits); + root.put("generationRules", generationRules); + root.put("worldEntitySpawnBindings", spawnBindings); + try { + return objectMapper.writeValueAsBytes(root); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + /** + * Decodes only the exact canonical representation emitted by {@link #encode(ObjectMapper)}. This + * validates stored representation, not graph relationships or publication eligibility. + */ + static WorldAuthoredGraph decode(byte[] encoded, ObjectMapper objectMapper) { + if (encoded == null || objectMapper == null) { + throw malformed("World authored graph bytes or mapper are missing"); + } + byte[] original = encoded.clone(); + String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(original)) + .toString(); + } catch (CharacterCodingException exception) { + throw malformed("World authored graph bytes are not valid UTF-8", exception); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(json); + } catch (JacksonException exception) { + throw malformed("World authored graph bytes are not strict JSON", exception); + } + requireObject(root, "root"); + requireFields( + root, + "root", + "snapshotSchemaVersion", + "regions", + "zones", + "rooms", + "roomExits", + "generationRules", + "worldEntitySpawnBindings"); + JsonNode schemaVersion = root.get("snapshotSchemaVersion"); + if (!schemaVersion.isInt() || schemaVersion.intValue() != SNAPSHOT_SCHEMA_VERSION) { + throw malformed("World authored graph snapshot schema version is unsupported"); + } + + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + decodeRows(root.get("regions"), "regions", WorldAuthoredGraph::decodeRegion), + decodeRows(root.get("zones"), "zones", WorldAuthoredGraph::decodeZone), + decodeRows(root.get("rooms"), "rooms", WorldAuthoredGraph::decodeRoom), + decodeRows(root.get("roomExits"), "roomExits", WorldAuthoredGraph::decodeRoomExit), + decodeRows( + root.get("generationRules"), + "generationRules", + WorldAuthoredGraph::decodeGenerationRule), + decodeRows( + root.get("worldEntitySpawnBindings"), + "worldEntitySpawnBindings", + WorldAuthoredGraph::decodeSpawnBinding)); + if (!Arrays.equals(graph.encode(objectMapper), original)) { + throw malformed("World authored graph bytes are not in canonical encoding"); + } + return graph; + } + + private static List> decodeRows( + JsonNode rows, String family, Function> decoder) { + if (rows == null || !rows.isArray()) { + throw malformed("World authored graph family " + family + " is not an array"); + } + List> decodedRows = new ArrayList<>(rows.size()); + for (JsonNode row : rows) { + decodedRows.add(decoder.apply(row)); + } + return decodedRows; + } + + private static LinkedHashMap decodeRegion(JsonNode row) { + requireFields( + row, + "regions row", + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "regions row")); + decoded.put("shardId", nonNegativeInt(row, "shardId", "regions row")); + decoded.put("name", nonBlankString(row, "name", "regions row")); + decoded.put("weather", nullableString(row, "weather", "regions row")); + decoded.put("generationSeed", longValue(row, "generationSeed", "regions row")); + decoded.put("generatorType", nullableString(row, "generatorType", "regions row")); + decoded.put("generatorParams", nullableString(row, "generatorParams", "regions row")); + JsonNode spacing = row.get("spacingMultiplier"); + if (spacing == null || !spacing.isFloatingPointNumber()) { + throw malformed("World authored graph regions row spacingMultiplier is not a Double"); + } + double spacingValue = spacing.doubleValue(); + if (!Double.isFinite(spacingValue) || spacingValue <= 0.0d) { + throw malformed("World authored graph regions row spacingMultiplier is unsupported"); + } + decoded.put("spacingMultiplier", spacingValue); + return decoded; + } + + private static LinkedHashMap decodeZone(JsonNode row) { + requireFields(row, "zones row", "id", "regionId", "name"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "zones row")); + decoded.put("regionId", positiveLong(row, "regionId", "zones row")); + decoded.put("name", nonBlankString(row, "name", "zones row")); + return decoded; + } + + private static LinkedHashMap decodeRoom(JsonNode row) { + requireFields( + row, + "rooms row", + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "rooms row")); + decoded.put("zoneId", positiveLong(row, "zoneId", "rooms row")); + decoded.put("name", nonBlankString(row, "name", "rooms row")); + decoded.put("description", nullableString(row, "description", "rooms row")); + decoded.put( + "nameLocalizedVariantsJson", nullableString(row, "nameLocalizedVariantsJson", "rooms row")); + decoded.put( + "descriptionLocalizedVariantsJson", + nullableString(row, "descriptionLocalizedVariantsJson", "rooms row")); + return decoded; + } + + private static LinkedHashMap decodeRoomExit(JsonNode row) { + requireFields(row, "roomExits row", "id", "fromRoomId", "toRoomId", "direction", "cost"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "roomExits row")); + decoded.put("fromRoomId", positiveLong(row, "fromRoomId", "roomExits row")); + decoded.put("toRoomId", positiveLong(row, "toRoomId", "roomExits row")); + decoded.put("direction", nonBlankString(row, "direction", "roomExits row")); + decoded.put("cost", positiveInt(row, "cost", "roomExits row")); + return decoded; + } + + private static LinkedHashMap decodeGenerationRule(JsonNode row) { + requireFields(row, "generationRules row", "id", "name", "scopeType", "scopeId", "value"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "generationRules row")); + decoded.put("name", nonBlankString(row, "name", "generationRules row")); + String scopeType = nullableString(row, "scopeType", "generationRules row"); + String scopeId = nullableString(row, "scopeId", "generationRules row"); + if ((scopeType == null) != (scopeId == null)) { + throw malformed("World authored graph generationRules row has a partial scope"); + } + if (scopeType != null + && (!scopeType.equals("REGION_SUBTREE") && !scopeType.equals("ZONE_SUBTREE"))) { + throw malformed("World authored graph generationRules row scopeType is unsupported"); + } + if (scopeId != null) { + try { + long parsedScopeId = Long.parseLong(scopeId); + if (parsedScopeId <= 0L || !Long.toString(parsedScopeId).equals(scopeId)) { + throw malformed("World authored graph generationRules row scopeId is noncanonical"); + } + } catch (NumberFormatException exception) { + throw malformed( + "World authored graph generationRules row scopeId is unsupported", exception); + } + } + decoded.put("scopeType", scopeType); + decoded.put("scopeId", scopeId); + decoded.put("value", nullableString(row, "value", "generationRules row")); + return decoded; + } + + private static LinkedHashMap decodeSpawnBinding(JsonNode row) { + requireFields( + row, + "worldEntitySpawnBindings row", + "id", + "roomId", + "entityTemplateType", + "entityTemplateId", + "spawnCount", + "respawnDelaySeconds"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "worldEntitySpawnBindings row")); + decoded.put("roomId", positiveLong(row, "roomId", "worldEntitySpawnBindings row")); + String entityType = nonBlankString(row, "entityTemplateType", "worldEntitySpawnBindings row"); + if (!entityType.equals("ITEM") && !entityType.equals("NPC")) { + throw malformed("World authored graph worldEntitySpawnBindings row type is unsupported"); + } + decoded.put("entityTemplateType", entityType); + decoded.put( + "entityTemplateId", positiveLong(row, "entityTemplateId", "worldEntitySpawnBindings row")); + decoded.put("spawnCount", positiveInt(row, "spawnCount", "worldEntitySpawnBindings row")); + decoded.put( + "respawnDelaySeconds", + nonNegativeInt(row, "respawnDelaySeconds", "worldEntitySpawnBindings row")); + return decoded; + } + + private static void requireFields(JsonNode object, String label, String... fields) { + requireObject(object, label); + Set expected = Set.of(fields); + if (object.size() != expected.size()) { + throw malformed("World authored graph " + label + " has missing or extra fields"); + } + for (Map.Entry entry : object.properties()) { + if (!expected.contains(entry.getKey())) { + throw malformed("World authored graph " + label + " has an unknown field"); + } + } + for (String field : fields) { + if (object.get(field) == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + } + } + + private static void requireObject(JsonNode node, String label) { + if (node == null || !node.isObject()) { + throw malformed("World authored graph " + label + " is not an object"); + } + } + + private static long positiveLong(JsonNode object, String field, String label) { + long value = longValue(object, field, label); + if (value <= 0L) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static long longValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw malformed("World authored graph " + label + " " + field + " is not a Long"); + } + return value.longValue(); + } + + private static int positiveInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value <= 0) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static int nonNegativeInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value < 0) { + throw malformed("World authored graph " + label + " " + field + " is negative"); + } + return value; + } + + private static int intValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw malformed("World authored graph " + label + " " + field + " is not an Integer"); + } + return value.intValue(); + } + + private static String nonBlankString(JsonNode object, String field, String label) { + String value = stringValue(object, field, label, false); + if (value.isBlank()) { + throw malformed("World authored graph " + label + " " + field + " is blank"); + } + return value; + } + + private static String nullableString(JsonNode object, String field, String label) { + return stringValue(object, field, label, true); + } + + private static String stringValue(JsonNode object, String field, String label, boolean nullable) { + JsonNode value = object.get(field); + if (value == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + if (value.isNull() && nullable) { + return null; + } + if (!value.isString()) { + throw malformed("World authored graph " + label + " " + field + " is not a string"); + } + return value.stringValue(); + } + + private static SnapshotConflictException malformed(String message) { + return new SnapshotConflictException(message); + } + + private static SnapshotConflictException malformed(String message, Exception cause) { + SnapshotConflictException failure = new SnapshotConflictException(message); + failure.initCause(cause); + return failure; + } + + WorldAuthoredGraph withRegions(List> updatedRegions) { + return new WorldAuthoredGraph( + updatedRegions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private static List> copyRows( + List> rows, boolean immutable) { + Objects.requireNonNull(rows, "rows"); + List> copiedRows = new ArrayList<>(rows.size()); + for (Map row : rows) { + Objects.requireNonNull(row, "row"); + LinkedHashMap copiedRow = new LinkedHashMap<>(); + for (Map.Entry entry : row.entrySet()) { + copiedRow.put( + Objects.requireNonNull(entry.getKey(), "row key"), + copyValue(entry.getValue(), immutable)); + } + copiedRows.add(immutable ? Collections.unmodifiableMap(copiedRow) : copiedRow); + } + return immutable ? Collections.unmodifiableList(copiedRows) : copiedRows; + } + + private static Object copyValue(Object value, boolean immutable) { + if (value == null + || value instanceof String + || value instanceof Byte + || value instanceof Short + || value instanceof Integer + || value instanceof Long + || value instanceof Float + || value instanceof Double + || value instanceof BigInteger + || value instanceof BigDecimal + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum) { + return value; + } + if (value instanceof byte[] bytes) { + return bytes.clone(); + } + if (value instanceof Map map) { + LinkedHashMap copiedMap = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw new IllegalArgumentException("Authored graph object keys must be strings"); + } + copiedMap.put(key, copyValue(entry.getValue(), immutable)); + } + return immutable ? Collections.unmodifiableMap(copiedMap) : copiedMap; + } + if (value instanceof List list) { + List copiedList = new ArrayList<>(list.size()); + for (Object item : list) { + copiedList.add(copyValue(item, immutable)); + } + return immutable ? Collections.unmodifiableList(copiedList) : copiedList; + } + throw new IllegalArgumentException( + "Unsupported mutable value in authored graph: " + value.getClass().getName()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java new file mode 100644 index 0000000000..3409cc3665 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; + +/** + * Shared internal six-family graph reader; callers must hold their exact owner transaction lock. + */ +final class WorldAuthoredGraphReader { + private static final Table REGION = table("region"); + private static final Table ZONE = table("zone"); + private static final Table ROOM = table("room"); + private static final Table ROOM_EXIT = table("room_exit"); + private static final Table GENERATION_RULE = table("generation_rule"); + private static final Table SPAWN_BINDING = table("world_entity_spawn_binding"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field REGION_ID = field("region_id", Long.class); + private static final Field ZONE_ID = field("zone_id", Long.class); + private static final Field FROM_ROOM_ID = field("from_room_id", Long.class); + private static final Field TO_ROOM_ID = field("to_room_id", Long.class); + private static final Field ROOM_ID = field("room_id", Long.class); + private static final Field GENERATION_SEED = field("generation_seed", Long.class); + private static final Field SHARD_ID = field("shard_id", Integer.class); + private static final Field NAME = field("name", String.class); + private static final Field WEATHER = field("weather", String.class); + private static final Field GENERATOR_TYPE = field("generator_type", String.class); + private static final Field GENERATOR_PARAMS = field("generator_params", String.class); + private static final Field SPACING_MULTIPLIER = field("spacing_multiplier", Double.class); + private static final Field DESCRIPTION = field("description", String.class); + private static final Field NAME_LOCALIZED_VARIANTS_JSON = + field("name_localized_variants_json", String.class); + private static final Field DESCRIPTION_LOCALIZED_VARIANTS_JSON = + field("description_localized_variants_json", String.class); + private static final Field DIRECTION = field("direction", String.class); + private static final Field COST = field("cost", Integer.class); + private static final Field SCOPE_TYPE = field("scope_type", String.class); + private static final Field SCOPE_ID = field("scope_id", String.class); + private static final Field RULE_VALUE = field("value", String.class); + private static final Field ENTITY_TEMPLATE_TYPE = + field("entity_template_type", String.class); + private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); + private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); + private static final Field RESPAWN_DELAY_SECONDS = + field("respawn_delay_seconds", Integer.class); + + private final DSLContext dsl; + + WorldAuthoredGraphReader(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { + List regionRows = fetch(REGION, tenantKey, versionKey); + List zoneRows = fetch(ZONE, tenantKey, versionKey); + List roomRows = fetch(ROOM, tenantKey, versionKey); + List exitRows = fetch(ROOM_EXIT, tenantKey, versionKey); + List ruleRows = fetch(GENERATION_RULE, tenantKey, versionKey); + List bindingRows = fetch(SPAWN_BINDING, tenantKey, versionKey); + + Map regionIds = new HashMap<>(); + Map zoneIds = new HashMap<>(); + Map roomIds = new HashMap<>(); + List> regions = new ArrayList<>(); + List> zones = new ArrayList<>(); + List> rooms = new ArrayList<>(); + List> exits = new ArrayList<>(); + List> rules = new ArrayList<>(); + List> bindings = new ArrayList<>(); + + for (Record row : regionRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "region.id"); + unique(regionIds, id, "region"); + Integer shard = required(row, SHARD_ID); + Long seed = required(row, GENERATION_SEED); + Double spacing = required(row, SPACING_MULTIPLIER); + String name = required(row, NAME); + if (shard < 0 || !Double.isFinite(spacing) || spacing <= 0.0d || name.isBlank()) { + throw incomplete("region", id, "unsupported required region data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("shardId", shard); + item.put("name", name); + item.put("weather", row.get(WEATHER, String.class)); + item.put("generationSeed", seed); + item.put("generatorType", row.get(GENERATOR_TYPE, String.class)); + item.put("generatorParams", row.get(GENERATOR_PARAMS, String.class)); + item.put("spacingMultiplier", spacing); + regions.add(item); + } + + for (Record row : zoneRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "zone.id"); + unique(zoneIds, id, "zone"); + long regionId = positive(row, REGION_ID, "zone.region_id"); + if (!regionIds.containsKey(regionId)) { + throw incomplete( + "zone", id, "region parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("zone", id, "zone name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("regionId", regionId); + item.put("name", name); + zones.add(item); + } + + for (Record row : roomRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room.id"); + unique(roomIds, id, "room"); + long zoneId = positive(row, ZONE_ID, "room.zone_id"); + if (!zoneIds.containsKey(zoneId)) { + throw incomplete("room", id, "zone parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("room", id, "room name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("zoneId", zoneId); + item.put("name", name); + item.put("description", row.get(DESCRIPTION, String.class)); + item.put("nameLocalizedVariantsJson", row.get(NAME_LOCALIZED_VARIANTS_JSON, String.class)); + item.put( + "descriptionLocalizedVariantsJson", + row.get(DESCRIPTION_LOCALIZED_VARIANTS_JSON, String.class)); + rooms.add(item); + } + + for (Record row : exitRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room_exit.id"); + long from = positive(row, FROM_ROOM_ID, "room_exit.from_room_id"); + long to = positive(row, TO_ROOM_ID, "room_exit.to_room_id"); + if (!roomIds.containsKey(from) || !roomIds.containsKey(to)) { + throw incomplete( + "room_exit", id, "exit endpoint is missing or belongs to another tenant/Version"); + } + String direction = required(row, DIRECTION); + Integer cost = required(row, COST); + if (direction.isBlank() || cost <= 0) { + throw incomplete("room_exit", id, "unsupported required room-exit data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("fromRoomId", from); + item.put("toRoomId", to); + item.put("direction", direction); + item.put("cost", cost); + exits.add(item); + } + + Set exactRuleKeys = new HashSet<>(); + Set unscopedRuleNames = new HashSet<>(); + for (Record row : ruleRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "generation_rule.id"); + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("generation_rule", id, "generation rule name is blank"); + } + String scopeType = row.get(SCOPE_TYPE, String.class); + String scopeId = row.get(SCOPE_ID, String.class); + if ((scopeType == null) != (scopeId == null)) { + throw incomplete( + "generation_rule", id, "scope_type and scope_id are only partially present"); + } + String stableScope; + if (scopeType == null) { + if (!unscopedRuleNames.add(name)) { + throw incomplete( + "generation_rule", id, "duplicate ambiguous unscoped generation rule name"); + } + stableScope = ""; + } else { + if (!"REGION_SUBTREE".equals(scopeType) && !"ZONE_SUBTREE".equals(scopeType)) { + throw incomplete("generation_rule", id, "unsupported generation rule scope type"); + } + long parsedScopeId = parseCanonicalPositiveId(scopeId, "generation_rule.scope_id", id); + if (("REGION_SUBTREE".equals(scopeType) && !regionIds.containsKey(parsedScopeId)) + || ("ZONE_SUBTREE".equals(scopeType) && !zoneIds.containsKey(parsedScopeId))) { + throw incomplete( + "generation_rule", id, "generation rule scope parent is missing or mismatched"); + } + stableScope = scopeType + ":" + scopeId; + } + if (!exactRuleKeys.add(stableScope + "\u0000" + name)) { + throw incomplete("generation_rule", id, "duplicate generation rule identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("name", name); + item.put("scopeType", scopeType); + item.put("scopeId", scopeId); + item.put("value", row.get(RULE_VALUE, String.class)); + rules.add(item); + } + + Set spawnKeys = new HashSet<>(); + for (Record row : bindingRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "world_entity_spawn_binding.id"); + long roomId = positive(row, ROOM_ID, "world_entity_spawn_binding.room_id"); + if (!roomIds.containsKey(roomId)) { + throw incomplete( + "world_entity_spawn_binding", + id, + "spawn room is missing or belongs to another tenant/Version"); + } + String entityType = required(row, ENTITY_TEMPLATE_TYPE); + Long entityId = required(row, ENTITY_TEMPLATE_ID); + Integer spawnCount = required(row, SPAWN_COUNT); + Integer delay = required(row, RESPAWN_DELAY_SECONDS); + if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) + || entityId <= 0L + || spawnCount <= 0 + || delay < 0) { + throw incomplete( + "world_entity_spawn_binding", id, "unsupported required spawn binding data"); + } + String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; + if (!spawnKeys.add(spawnKey)) { + throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("roomId", roomId); + item.put("entityTemplateType", entityType); + item.put("entityTemplateId", entityId); + item.put("spawnCount", spawnCount); + item.put("respawnDelaySeconds", delay); + bindings.add(item); + } + return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); + } + + private List fetch(Table table, long tenantKey, long versionKey) { + List fetchedRows = + dsl.selectFrom(table) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionKey))) + .orderBy(ID.asc()) + .fetch(); + List rows = new ArrayList<>(fetchedRows.size()); + rows.addAll(fetchedRows); + return rows; + } + + private void requireExactScope(Record row, long tenantKey, long versionKey) { + if (!Objects.equals(row.get(TENANT_ID, Long.class), tenantKey) + || !Objects.equals(row.get(VERSION_ID, Long.class), versionKey)) { + throw new SnapshotConflictException( + "World graph row returned outside the exact V27 tenant/Version scope"); + } + } + + private long positive(Record row, Field field, String label) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new SnapshotConflictException(label + " is missing or non-positive"); + } + return value; + } + + private long parseCanonicalPositiveId(String value, String label, long rowId) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new NumberFormatException("not canonical positive decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw incomplete("generation_rule", rowId, label + " is unsupported"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private SnapshotConflictException incomplete(String family, long id, String reason) { + return new SnapshotConflictException( + "World graph capture denied incomplete " + family + " row " + id + ": " + reason); + } + + private void unique(Map ids, long id, String family) { + if (ids.putIfAbsent(id, Boolean.TRUE) != null) { + throw incomplete(family, id, "duplicate row identity"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java new file mode 100644 index 0000000000..d6fd95deb4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable, owner-private capture of the six authored World template families. */ +public record WorldAuthoredGraphSnapshot( + UUID snapshotId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + short ownerBindingSchemaVersion, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String captureRequestDigest, + String suppliedOwnedAffectedTuplesJson, + String ownerRevisionEvidenceJson, + byte[] graphBytes, + String graphSha256, + OwnerCommitProofStatus ownerCommitProofStatus) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public WorldAuthoredGraphSnapshot { + requireNonNil(snapshotId, "snapshotId"); + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requireText(worldSlug, "worldSlug"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + requirePositive(localVersionKey, "localVersionKey"); + requirePositive(localTenantKey, "localTenantKey"); + if (ownerBindingSchemaVersion != 1) { + throw new IllegalArgumentException( + "World snapshot requires exact V27 owner binding schema 1"); + } + requireNonNil(intakeOperationId, "intakeOperationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requirePrefixedSha256(intakeRequestDigest, "intakeRequestDigest"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requirePrefixedSha256(sourceEvidenceDigest, "sourceEvidenceDigest"); + requirePrefixedSha256(intakeReceiptDigest, "intakeReceiptDigest"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph snapshot requires retained schema 2 or current schema 3"); + } + requireSha256(captureRequestDigest, "captureRequestDigest"); + requireText(suppliedOwnedAffectedTuplesJson, "suppliedOwnedAffectedTuplesJson"); + requireText(ownerRevisionEvidenceJson, "ownerRevisionEvidenceJson"); + graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + if (graphBytes.length == 0) { + throw new IllegalArgumentException("graphBytes must contain a complete graph representation"); + } + requireSha256(graphSha256, "graphSha256"); + Objects.requireNonNull(ownerCommitProofStatus, "ownerCommitProofStatus"); + if (ownerCommitProofStatus != OwnerCommitProofStatus.CAPTURED_UNVERIFIED) { + throw new IllegalArgumentException( + "This component cannot claim complete owner commit application proof"); + } + } + + @Override + public byte[] graphBytes() { + return graphBytes.clone(); + } + + /** Proof state is deliberately non-eligible until the complete World commit fence is wired. */ + public enum OwnerCommitProofStatus { + CAPTURED_UNVERIFIED + } + + /** One supplied World-owned affected tuple, retained as input evidence without validating it. */ + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("World snapshot tuples must name WORLD_MANAGEMENT"); + } + requireText(aggregateType, "aggregateType"); + requireText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException( + "scopeType and scopeId must be both present or both absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + } + + /** Exact external binding. All private World keys are resolved from immutable owner records. */ + public record CaptureRequest( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List suppliedOwnedAffectedTuples) { + public CaptureRequest { + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph capture request requires retained schema 2 or current schema 3"); + } + Objects.requireNonNull(suppliedOwnedAffectedTuples, "suppliedOwnedAffectedTuples"); + List ordered = new ArrayList<>(suppliedOwnedAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + for (int index = 1; index < ordered.size(); index++) { + if (ordered.get(index - 1).equals(ordered.get(index))) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + } + suppliedOwnedAffectedTuples = List.copyOf(ordered); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " is required"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be 64 lowercase hexadecimal digits"); + } + } + + private static void requirePrefixedSha256(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java new file mode 100644 index 0000000000..c1767c1e1a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -0,0 +1,329 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.OwnerProvenance; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal-only World graph snapshot capture. Captured rows are representation evidence, not + * publication eligibility or proof that World applied a complete synchronized owner commit. + */ +public class WorldAuthoredGraphSnapshotCapture { + private static final int WORLD_DIGEST_SCHEMA_VERSION = 3; + + private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + + private static final Field COMMIT_ID = field("commit_id", String.class); + private static final Field REVISION_ID = field("revision_id", String.class); + private static final Field OPERATION_TYPE = field("operation_type", String.class); + private static final Field AGGREGATE_TYPE = field("aggregate_type", String.class); + private static final Field REQUESTED_AGGREGATE_ID = + field("requested_aggregate_id", String.class); + private static final Field APPLIED_AGGREGATE_ID = field("applied_aggregate_id", Long.class); + private static final Field RESULT = field("result", String.class); + private static final Field AGGREGATE_EPOCH_AFTER = + field("aggregate_epoch_after", Long.class); + private static final Field SCOPE_EPOCH_AFTER = field("scope_epoch_after", Long.class); + + private final DSLContext dsl; + private final WorldAuthoredGraphReader graphReader; + private final WorldDraftDesignDigestService draftDigestService; + private final WorldAuthoredGraphSnapshotRepository snapshotRepository; + private final ObjectMapper objectMapper; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected World collaborators are internal; construction acquires no resources and this class has no finalizer.") + public WorldAuthoredGraphSnapshotCapture( + DSLContext dsl, + WorldDraftDesignDigestService draftDigestService, + WorldAuthoredGraphSnapshotRepository snapshotRepository, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.graphReader = new WorldAuthoredGraphReader(dsl); + this.draftDigestService = + Objects.requireNonNull(draftDigestService, "draftDigestService must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); + } + + /** + * Captures the current six-family authored graph while holding the exact V25 owner row. + * + *

The caller owns the writable READ COMMITTED transaction. This method is deliberately unwired + * from public publication/activation surfaces and persists every result as {@code + * CAPTURED_UNVERIFIED}; V19 currently lacks the revision-to-complete-scope proof needed to claim + * synchronized owner application. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + OwnerProvenance provenance = snapshotRepository.lockAndResolve(request); + String tuplesJson = encodeTuples(request.suppliedOwnedAffectedTuples()); + String captureRequestDigest = captureRequestDigest(request, provenance, tuplesJson); + + WorldAuthoredGraphSnapshot prior = snapshotRepository.findByFence(request.publicationFence()); + if (prior != null) { + snapshotRepository.requireSameRequest( + prior, request, provenance, captureRequestDigest, tuplesJson); + return prior; + } + if (request.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION) { + throw new SnapshotConflictException("New World graph capture requires digest schema 3"); + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new SnapshotConflictException( + "World graph capture cannot create a new snapshot after its V25 fence leaves FROZEN"); + } + + String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); + WorldAuthoredGraph graph = + graphReader.readAndValidateGraph(provenance.localTenantKey(), provenance.localVersionKey()); + byte[] graphBytes = graph.encode(objectMapper); + WorldDraftDesignDigest currentDigest = + draftDigestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(currentDigest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(currentDigest.scopeValue()) + || currentDigest.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION + || !request.contentDigest().equals(currentDigest.contentDigest())) { + throw new SnapshotConflictException( + "World graph capture differs from the V25 frozen checkpoint under the V27 private Version key"); + } + + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + newNonNilUuid(), + provenance.targetNamespace(), + provenance.canonicalTenantId(), + provenance.canonicalVersionId(), + provenance.versionIdentityOperationId(), + provenance.worldSlug(), + provenance.gameDesignVersionId(), + provenance.localVersionKey(), + provenance.localTenantKey(), + (short) 1, + provenance.intakeOperationId(), + provenance.intakeRequestId(), + provenance.intakeRequestDigest(), + provenance.sourceOperationId(), + provenance.sourceEvidenceDigest(), + provenance.intakeReceiptDigest(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + captureRequestDigest, + tuplesJson, + revisionEvidenceJson, + graphBytes, + sha256(graphBytes), + OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + return snapshotRepository.insertAndReadback(snapshot); + } + + private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvenance provenance) { + Result rows = + dsl.select( + ID, + COMMIT_ID, + REVISION_ID, + OPERATION_TYPE, + AGGREGATE_TYPE, + REQUESTED_AGGREGATE_ID, + APPLIED_AGGREGATE_ID, + RESULT, + AGGREGATE_EPOCH_AFTER, + SCOPE_EPOCH_AFTER) + .from(REVISION_LEDGER) + .where( + TENANT_ID + .eq(provenance.localTenantKey()) + .and(VERSION_ID.eq(provenance.localVersionKey())) + .and(COMMIT_ID.eq(request.appliedCommitId()))) + .orderBy(ID.asc()) + .fetch(); + if (rows.isEmpty()) { + throw new WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException( + "World graph capture requires retained V19 revision history for the named commit"); + } + List> evidence = new ArrayList<>(); + for (Record row : rows) { + if (!"APPLIED".equals(row.get(RESULT, String.class))) { + throw new SnapshotConflictException( + "World graph capture encountered non-APPLIED V19 revision history"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", required(row, ID)); + item.put("commitId", required(row, COMMIT_ID)); + item.put("revisionId", required(row, REVISION_ID)); + item.put("operationType", required(row, OPERATION_TYPE)); + item.put("aggregateType", required(row, AGGREGATE_TYPE)); + item.put("requestedAggregateId", required(row, REQUESTED_AGGREGATE_ID)); + item.put("appliedAggregateId", required(row, APPLIED_AGGREGATE_ID)); + item.put("result", required(row, RESULT)); + item.put("aggregateEpochAfter", required(row, AGGREGATE_EPOCH_AFTER)); + item.put("scopeEpochAfter", row.get(SCOPE_EPOCH_AFTER, Long.class)); + evidence.add(item); + } + return writeJson(evidence); + } + + private String encodeTuples(List tuples) { + List> values = new ArrayList<>(); + for (OwnedAffectedTuple tuple : tuples) { + LinkedHashMap item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + values.add(item); + } + return writeJson(values); + } + + private String captureRequestDigest( + CaptureRequest request, OwnerProvenance provenance, String tuplesJson) { + LinkedHashMap binding = new LinkedHashMap<>(); + binding.put("targetNamespace", request.targetNamespace()); + binding.put("canonicalTenantId", request.canonicalTenantId().toString()); + binding.put("canonicalVersionId", request.canonicalVersionId().toString()); + binding.put("versionIdentityOperationId", provenance.versionIdentityOperationId().toString()); + binding.put("worldSlug", provenance.worldSlug()); + binding.put("gameDesignVersionId", provenance.gameDesignVersionId()); + binding.put("localVersionKey", provenance.localVersionKey()); + binding.put("localTenantKey", provenance.localTenantKey()); + binding.put("intakeOperationId", provenance.intakeOperationId().toString()); + binding.put("intakeRequestId", request.intakeRequestId().toString()); + binding.put("intakeRequestDigest", provenance.intakeRequestDigest()); + binding.put("sourceOperationId", provenance.sourceOperationId().toString()); + binding.put("sourceEvidenceDigest", provenance.sourceEvidenceDigest()); + binding.put("intakeReceiptDigest", provenance.intakeReceiptDigest()); + binding.put("publicationFence", request.publicationFence().toString()); + binding.put("publicationRequestId", request.publicationRequestId()); + binding.put("requestDigest", request.requestDigest()); + binding.put("versionStateEpoch", request.versionStateEpoch()); + binding.put("publishWorkflowId", request.publishWorkflowId()); + binding.put("appliedCommitId", request.appliedCommitId()); + binding.put("contentDigest", request.contentDigest()); + binding.put("digestSchemaVersion", request.digestSchemaVersion()); + binding.put("suppliedOwnedAffectedTuplesJson", tuplesJson); + return sha256(writeJsonBytes(binding)); + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph evidence could not be encoded"); + } + } + + private byte[] writeJsonBytes(Object value) { + try { + return objectMapper.writeValueAsBytes(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder builder = new StringBuilder(digest.length * 2); + for (byte current : digest) { + builder.append(String.format("%02x", current)); + } + return builder.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java new file mode 100644 index 0000000000..749d06c7f6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java @@ -0,0 +1,599 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-private persistence for immutable World authored graph captures. */ +@Repository +public class WorldAuthoredGraphSnapshotRepository { + private static final String FROZEN = "FROZEN"; + private static final Set RETAINED_FENCE_PHASES = + Set.of(FROZEN, "PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED"); + private static final String CAPTURED_UNVERIFIED = "CAPTURED_UNVERIFIED"; + + private static final Table SNAPSHOT = DSL.table(DSL.name("world_authored_graph_snapshot")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + private static final Table FENCE_OWNER = + DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table FENCE_ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + + private static final Field SNAPSHOT_ID = field("snapshot_id", UUID.class); + private static final Field CAPTURE_REQUEST_DIGEST = + field("capture_request_digest", String.class); + private static final Field PUBLICATION_FENCE = field("publication_fence", UUID.class); + private static final Field TARGET_NAMESPACE = field("target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field WORLD_SLUG = field("world_slug", String.class); + private static final Field GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field REQUEST_DIGEST = field("request_digest", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field APPLIED_COMMIT_ID = field("applied_commit_id", String.class); + private static final Field CONTENT_DIGEST = field("content_digest", String.class); + private static final Field DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + private static final Field SUPPLIED_TUPLES_JSON = + field("supplied_owned_affected_tuples_json", String.class); + private static final Field OWNER_REVISION_EVIDENCE_JSON = + field("owner_revision_evidence_json", String.class); + private static final Field OWNER_COMMIT_PROOF_STATUS = + field("owner_commit_proof_status", String.class); + private static final Field GRAPH_BYTES = field("graph_bytes", byte[].class); + private static final Field GRAPH_SHA256 = field("graph_sha256", String.class); + + private static final Field VERSION_OPERATION_ID = field("operation_id", UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + + private static final Field INTAKE_OPERATION = field("operation_id", UUID.class); + private static final Field INTAKE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field INTAKE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INTAKE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field INTAKE_REQUEST = field("intake_request_id", UUID.class); + private static final Field INTAKE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field INTAKE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT = field("receipt_digest", String.class); + private static final Field INTAKE_WORLD_SLUG = field("world_slug", String.class); + + private static final Field OWNER_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field OWNER_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field OWNER_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_VERSION_ID = field("version_id", Long.class); + private static final Field OWNER_FREEZE_PHASE = field("owner_freeze_phase", String.class); + private static final Field OWNER_CURRENT_FENCE = + field("current_publication_fence", UUID.class); + + private static final Field ATTEMPT_FENCE = field("publication_fence", UUID.class); + private static final Field ATTEMPT_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field ATTEMPT_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field ATTEMPT_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field ATTEMPT_VERSION_ID = field("version_id", Long.class); + private static final Field ATTEMPT_OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field ATTEMPT_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field ATTEMPT_VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field ATTEMPT_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field ATTEMPT_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field ATTEMPT_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field ATTEMPT_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field ATTEMPT_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field ATTEMPT_PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field ATTEMPT_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field ATTEMPT_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field ATTEMPT_PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field ATTEMPT_APPLIED_COMMIT_ID = + field("applied_commit_id", String.class); + private static final Field ATTEMPT_CONTENT_DIGEST = field("content_digest", String.class); + private static final Field ATTEMPT_DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredGraphSnapshotRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Resolves all private keys and locks the existing V25 FROZEN owner row. */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProvenance lockAndResolve(CaptureRequest request) { + requireWritableReadCommittedOwnerTransaction(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where( + VERSION_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(VERSION_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(VERSION_CANONICAL_VERSION_ID.eq(request.canonicalVersionId())) + .and(VERSION_INTAKE_REQUEST_ID.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (version == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an exact retained V27 authored-Version identity"); + } + Record intake = + dsl.selectFrom(SOURCE_INTAKE) + .where( + INTAKE_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(INTAKE_REQUEST.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (intake == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the exact retained authored-source intake"); + } + Record owner = + dsl.selectFrom(FENCE_OWNER) + .where( + OWNER_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(OWNER_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(OWNER_VERSION_ID.eq(required(version, VERSION_LOCAL_VERSION_KEY)))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an existing V25 shared publication-fence owner row"); + } + String ownerFreezePhase = owner.get(OWNER_FREEZE_PHASE, String.class); + OwnerProvenance provenance = toProvenance(version, ownerFreezePhase); + requireExactIntake(intake, request, provenance); + if (!Objects.equals(owner.get(OWNER_LOCAL_TENANT_KEY), provenance.localTenantKey()) + || !RETAINED_FENCE_PHASES.contains(ownerFreezePhase) + || !request.publicationFence().equals(owner.get(OWNER_CURRENT_FENCE, UUID.class))) { + throw new SnapshotConflictException( + "World graph capture requires the exact retained V25 owner binding"); + } + + Record attempt = + dsl.selectFrom(FENCE_ATTEMPT) + .where( + ATTEMPT_FENCE + .eq(request.publicationFence()) + .and(ATTEMPT_TARGET_NAMESPACE.eq(request.targetNamespace())) + .and(ATTEMPT_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(ATTEMPT_LOCAL_TENANT_KEY.eq(provenance.localTenantKey())) + .and(ATTEMPT_VERSION_ID.eq(provenance.localVersionKey()))) + .forShare() + .fetchOne(); + if (attempt == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the immutable V25 publication attempt"); + } + requireExactAttempt(attempt, request, provenance); + return provenance; + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot findByFence(UUID publicationFence) { + Record row = + dsl.selectFrom(SNAPSHOT) + .where(PUBLICATION_FENCE.eq(Objects.requireNonNull(publicationFence))) + .fetchOne(); + return row == null ? null : toSnapshot(row); + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot insertAndReadback(WorldAuthoredGraphSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + int inserted = + dsl.insertInto(SNAPSHOT) + .set(SNAPSHOT_ID, snapshot.snapshotId()) + .set(CAPTURE_REQUEST_DIGEST, snapshot.captureRequestDigest()) + .set(PUBLICATION_FENCE, snapshot.publicationFence()) + .set(TARGET_NAMESPACE, snapshot.targetNamespace()) + .set(CANONICAL_TENANT_ID, snapshot.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, snapshot.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, snapshot.versionIdentityOperationId()) + .set(WORLD_SLUG, snapshot.worldSlug()) + .set(GAME_DESIGN_VERSION_ID, snapshot.gameDesignVersionId()) + .set(LOCAL_VERSION_KEY, snapshot.localVersionKey()) + .set(LOCAL_TENANT_KEY, snapshot.localTenantKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, snapshot.ownerBindingSchemaVersion()) + .set(INTAKE_OPERATION_ID, snapshot.intakeOperationId()) + .set(INTAKE_REQUEST_ID, snapshot.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, snapshot.intakeRequestDigest()) + .set(SOURCE_OPERATION_ID, snapshot.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, snapshot.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, snapshot.intakeReceiptDigest()) + .set(PUBLICATION_REQUEST_ID, snapshot.publicationRequestId()) + .set(REQUEST_DIGEST, snapshot.requestDigest()) + .set(VERSION_STATE_EPOCH, snapshot.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, snapshot.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, snapshot.appliedCommitId()) + .set(CONTENT_DIGEST, snapshot.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, snapshot.digestSchemaVersion()) + .set(SUPPLIED_TUPLES_JSON, snapshot.suppliedOwnedAffectedTuplesJson()) + .set(OWNER_REVISION_EVIDENCE_JSON, snapshot.ownerRevisionEvidenceJson()) + .set(OWNER_COMMIT_PROOF_STATUS, CAPTURED_UNVERIFIED) + .set(GRAPH_BYTES, snapshot.graphBytes()) + .set(GRAPH_SHA256, snapshot.graphSha256()) + .execute(); + if (inserted != 1) { + throw new SnapshotConflictException("World authored graph snapshot was not inserted"); + } + Record row = dsl.selectFrom(SNAPSHOT).where(SNAPSHOT_ID.eq(snapshot.snapshotId())).fetchOne(); + if (row == null) { + throw new SnapshotConflictException( + "World authored graph snapshot disappeared before immutable readback"); + } + WorldAuthoredGraphSnapshot stored = toSnapshot(row); + requireSameSnapshot(snapshot, stored); + return stored; + } + + public void requireSameRequest( + WorldAuthoredGraphSnapshot snapshot, + CaptureRequest request, + OwnerProvenance provenance, + String captureRequestDigest, + String tuplesJson) { + if (!snapshot.targetNamespace().equals(request.targetNamespace()) + || !snapshot.canonicalTenantId().equals(request.canonicalTenantId()) + || !snapshot.canonicalVersionId().equals(request.canonicalVersionId()) + || !snapshot.versionIdentityOperationId().equals(provenance.versionIdentityOperationId()) + || !snapshot.worldSlug().equals(provenance.worldSlug()) + || snapshot.gameDesignVersionId() != provenance.gameDesignVersionId() + || snapshot.localVersionKey() != provenance.localVersionKey() + || snapshot.localTenantKey() != provenance.localTenantKey() + || snapshot.ownerBindingSchemaVersion() != 1 + || !snapshot.intakeOperationId().equals(provenance.intakeOperationId()) + || !snapshot.intakeRequestId().equals(request.intakeRequestId()) + || !snapshot.intakeRequestDigest().equals(provenance.intakeRequestDigest()) + || !snapshot.sourceOperationId().equals(provenance.sourceOperationId()) + || !snapshot.sourceEvidenceDigest().equals(provenance.sourceEvidenceDigest()) + || !snapshot.intakeReceiptDigest().equals(provenance.intakeReceiptDigest()) + || !snapshot.publicationFence().equals(request.publicationFence()) + || !snapshot.publicationRequestId().equals(request.publicationRequestId()) + || !snapshot.requestDigest().equals(request.requestDigest()) + || snapshot.versionStateEpoch() != request.versionStateEpoch() + || !snapshot.publishWorkflowId().equals(request.publishWorkflowId()) + || !snapshot.appliedCommitId().equals(request.appliedCommitId()) + || !snapshot.contentDigest().equals(request.contentDigest()) + || snapshot.digestSchemaVersion() != request.digestSchemaVersion() + || !snapshot.captureRequestDigest().equals(captureRequestDigest) + || !snapshot.suppliedOwnedAffectedTuplesJson().equals(tuplesJson)) { + throw new SnapshotConflictException( + "World graph capture identity was reused with changed source or request binding"); + } + verifyGraphHash(snapshot); + } + + private OwnerProvenance toProvenance(Record version, String ownerFreezePhase) { + return new OwnerProvenance( + required(version, VERSION_OPERATION_ID), + required(version, VERSION_TARGET_NAMESPACE), + required(version, VERSION_CANONICAL_TENANT_ID), + required(version, VERSION_CANONICAL_VERSION_ID), + required(version, VERSION_WORLD_SLUG), + required(version, VERSION_GAME_DESIGN_VERSION_ID), + required(version, VERSION_LOCAL_VERSION_KEY), + required(version, VERSION_LOCAL_TENANT_KEY), + required(version, VERSION_INTAKE_OPERATION_ID), + required(version, VERSION_INTAKE_REQUEST_ID), + required(version, VERSION_INTAKE_REQUEST_DIGEST), + required(version, VERSION_SOURCE_OPERATION_ID), + required(version, VERSION_SOURCE_EVIDENCE_DIGEST), + required(version, VERSION_INTAKE_RECEIPT_DIGEST), + ownerFreezePhase); + } + + private void requireExactIntake( + Record intake, CaptureRequest request, OwnerProvenance provenance) { + if (!request.targetNamespace().equals(intake.get(INTAKE_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(intake.get(INTAKE_CANONICAL_TENANT_ID, UUID.class)) + || !request.intakeRequestId().equals(intake.get(INTAKE_REQUEST, UUID.class)) + || !provenance.intakeOperationId().equals(intake.get(INTAKE_OPERATION, UUID.class)) + || !provenance.intakeRequestDigest().equals(intake.get("request_digest", String.class)) + || !Objects.equals( + provenance.localTenantKey(), intake.get(INTAKE_LOCAL_TENANT_KEY, Long.class)) + || !provenance + .sourceOperationId() + .equals(intake.get(INTAKE_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(intake.get(INTAKE_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance.intakeReceiptDigest().equals(intake.get(INTAKE_RECEIPT, String.class)) + || !provenance.worldSlug().equals(intake.get(INTAKE_WORLD_SLUG, String.class))) { + throw new SnapshotConflictException( + "World Version provenance differs from its exact authored-source intake"); + } + } + + private void requireExactAttempt( + Record attempt, CaptureRequest request, OwnerProvenance provenance) { + if (!request.publicationFence().equals(attempt.get(ATTEMPT_FENCE, UUID.class)) + || !request.targetNamespace().equals(attempt.get(ATTEMPT_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(attempt.get(ATTEMPT_CANONICAL_TENANT_ID, UUID.class)) + || !Objects.equals( + provenance.localTenantKey(), attempt.get(ATTEMPT_LOCAL_TENANT_KEY, Long.class)) + || !Objects.equals( + provenance.localVersionKey(), attempt.get(ATTEMPT_VERSION_ID, Long.class)) + || !Short.valueOf((short) 1) + .equals(attempt.get(ATTEMPT_OWNER_BINDING_SCHEMA_VERSION, Short.class)) + || !request + .canonicalVersionId() + .equals(attempt.get(ATTEMPT_CANONICAL_VERSION_ID, UUID.class)) + || !provenance + .versionIdentityOperationId() + .equals(attempt.get(ATTEMPT_VERSION_IDENTITY_OPERATION_ID, UUID.class)) + || !Objects.equals( + provenance.gameDesignVersionId(), + attempt.get(ATTEMPT_GAME_DESIGN_VERSION_ID, Long.class)) + || !provenance + .intakeOperationId() + .equals(attempt.get(ATTEMPT_INTAKE_OPERATION_ID, UUID.class)) + || !request.intakeRequestId().equals(attempt.get(ATTEMPT_INTAKE_REQUEST_ID, UUID.class)) + || !provenance + .intakeRequestDigest() + .equals(attempt.get(ATTEMPT_INTAKE_REQUEST_DIGEST, String.class)) + || !provenance + .sourceOperationId() + .equals(attempt.get(ATTEMPT_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(attempt.get(ATTEMPT_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance + .intakeReceiptDigest() + .equals(attempt.get(ATTEMPT_INTAKE_RECEIPT_DIGEST, String.class)) + || !request + .publicationRequestId() + .equals(attempt.get(ATTEMPT_PUBLICATION_REQUEST_ID, String.class)) + || !request.requestDigest().equals(attempt.get(ATTEMPT_REQUEST_DIGEST, String.class)) + || request.versionStateEpoch() != attempt.get(ATTEMPT_VERSION_STATE_EPOCH, Long.class) + || !request + .publishWorkflowId() + .equals(attempt.get(ATTEMPT_PUBLISH_WORKFLOW_ID, String.class)) + || !request.appliedCommitId().equals(attempt.get(ATTEMPT_APPLIED_COMMIT_ID, String.class)) + || !request.contentDigest().equals(attempt.get(ATTEMPT_CONTENT_DIGEST, String.class)) + || request.digestSchemaVersion() + != attempt.get(ATTEMPT_DIGEST_SCHEMA_VERSION, Integer.class)) { + throw new SnapshotConflictException( + "World graph capture differs from the complete immutable V25 freeze attempt"); + } + } + + private WorldAuthoredGraphSnapshot toSnapshot(Record row) { + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + required(row, SNAPSHOT_ID), + required(row, TARGET_NAMESPACE), + required(row, CANONICAL_TENANT_ID), + required(row, CANONICAL_VERSION_ID), + required(row, VERSION_IDENTITY_OPERATION_ID), + required(row, WORLD_SLUG), + required(row, GAME_DESIGN_VERSION_ID), + required(row, LOCAL_VERSION_KEY), + required(row, LOCAL_TENANT_KEY), + required(row, OWNER_BINDING_SCHEMA_VERSION), + required(row, INTAKE_OPERATION_ID), + required(row, INTAKE_REQUEST_ID), + required(row, INTAKE_REQUEST_DIGEST), + required(row, SOURCE_OPERATION_ID), + required(row, SOURCE_EVIDENCE_DIGEST), + required(row, INTAKE_RECEIPT_DIGEST), + required(row, PUBLICATION_FENCE), + required(row, PUBLICATION_REQUEST_ID), + required(row, REQUEST_DIGEST), + required(row, VERSION_STATE_EPOCH), + required(row, PUBLISH_WORKFLOW_ID), + required(row, APPLIED_COMMIT_ID), + required(row, CONTENT_DIGEST), + required(row, DIGEST_SCHEMA_VERSION), + required(row, CAPTURE_REQUEST_DIGEST), + required(row, SUPPLIED_TUPLES_JSON), + required(row, OWNER_REVISION_EVIDENCE_JSON), + required(row, GRAPH_BYTES), + required(row, GRAPH_SHA256), + parseProofStatus(required(row, OWNER_COMMIT_PROOF_STATUS))); + verifyGraphHash(snapshot); + return snapshot; + } + + private OwnerCommitProofStatus parseProofStatus(String value) { + if (!CAPTURED_UNVERIFIED.equals(value)) { + throw new SnapshotConflictException("Unsupported World owner commit proof status"); + } + return OwnerCommitProofStatus.CAPTURED_UNVERIFIED; + } + + private void requireSameSnapshot( + WorldAuthoredGraphSnapshot expected, WorldAuthoredGraphSnapshot stored) { + if (!expected.snapshotId().equals(stored.snapshotId()) + || !expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.canonicalVersionId().equals(stored.canonicalVersionId()) + || !expected.versionIdentityOperationId().equals(stored.versionIdentityOperationId()) + || !expected.worldSlug().equals(stored.worldSlug()) + || expected.gameDesignVersionId() != stored.gameDesignVersionId() + || expected.localVersionKey() != stored.localVersionKey() + || expected.localTenantKey() != stored.localTenantKey() + || expected.ownerBindingSchemaVersion() != stored.ownerBindingSchemaVersion() + || !expected.intakeOperationId().equals(stored.intakeOperationId()) + || !expected.intakeRequestId().equals(stored.intakeRequestId()) + || !expected.intakeRequestDigest().equals(stored.intakeRequestDigest()) + || !expected.sourceOperationId().equals(stored.sourceOperationId()) + || !expected.sourceEvidenceDigest().equals(stored.sourceEvidenceDigest()) + || !expected.intakeReceiptDigest().equals(stored.intakeReceiptDigest()) + || !expected.publicationFence().equals(stored.publicationFence()) + || !expected.publicationRequestId().equals(stored.publicationRequestId()) + || !expected.requestDigest().equals(stored.requestDigest()) + || expected.versionStateEpoch() != stored.versionStateEpoch() + || !expected.publishWorkflowId().equals(stored.publishWorkflowId()) + || !expected.appliedCommitId().equals(stored.appliedCommitId()) + || !expected.contentDigest().equals(stored.contentDigest()) + || expected.digestSchemaVersion() != stored.digestSchemaVersion() + || !expected.captureRequestDigest().equals(stored.captureRequestDigest()) + || !expected + .suppliedOwnedAffectedTuplesJson() + .equals(stored.suppliedOwnedAffectedTuplesJson()) + || !expected.ownerRevisionEvidenceJson().equals(stored.ownerRevisionEvidenceJson()) + || !Arrays.equals(expected.graphBytes(), stored.graphBytes()) + || !expected.graphSha256().equals(stored.graphSha256()) + || expected.ownerCommitProofStatus() != stored.ownerCommitProofStatus()) { + throw new SnapshotConflictException( + "World graph snapshot differs from its immutable committed readback"); + } + } + + private void verifyGraphHash(WorldAuthoredGraphSnapshot snapshot) { + if (!WorldAuthoredGraphSnapshotCapture.sha256(snapshot.graphBytes()) + .equals(snapshot.graphSha256())) { + throw new SnapshotConflictException( + "World authored graph snapshot bytes failed their stored SHA-256 readback"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field); + if (value == null) { + throw new SnapshotConflictException( + "World graph snapshot is missing required " + field.getName()); + } + return value; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + public record OwnerProvenance( + UUID versionIdentityOperationId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String ownerFreezePhase) {} + + public static class SnapshotConflictException extends IllegalStateException { + public SnapshotConflictException(String message) { + super(message); + } + } + + public static class MissingOwnerHistoryException extends IllegalStateException { + public MissingOwnerHistoryException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java new file mode 100644 index 0000000000..70cd6a560c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; + +/** Owner-private, validated graph/2 storage view, never synchronized or released content. */ +public final class WorldCanonicalAuthoredGraph { + public enum Family { + REGION, + ZONE, + ROOM, + ROOM_EXIT, + GENERATION_RULE, + WORLD_ENTITY_SPAWN_BINDING + } + + /** Family is part of identity: equal UUIDs in different families are distinct templates. */ + public record Template(Family family, UUID templateId) { + public Template { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(templateId, "templateId"); + if (templateId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Canonical template ID must be non-nil"); + } + } + } + + /** Private World selectors never become Entity selectors or public template identifiers. */ + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public record Row( + Template template, + long mappingKey, + long privateRowKey, + Node authored, + WorldDesignMutationRevision content) { + public Row { + Objects.requireNonNull(template, "template"); + Objects.requireNonNull(authored, "authored"); + Objects.requireNonNull(content, "content"); + if (mappingKey <= 0 || privateRowKey <= 0) { + throw new IllegalArgumentException("World private keys must be positive"); + } + } + + public Template scope() { + boolean region = authored.mutation().getScopeType().name().endsWith("REGION_SUBTREE"); + return new Template(region ? Family.REGION : Family.ZONE, authored.scopeId()); + } + + public EntityTemplateReference entityReference() { + return authored.entityReference(); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final long localTenantKey; + private final long localVersionKey; + private final List rows; + + WorldCanonicalAuthoredGraph( + UUID tenantId, UUID versionId, long localTenantKey, long localVersionKey, List rows) { + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.versionId = Objects.requireNonNull(versionId, "versionId"); + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.rows = List.copyOf(rows); + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public List rows() { + return rows; + } + + public List family(Family family) { + return rows.stream().filter(row -> row.template().family() == family).toList(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java new file mode 100644 index 0000000000..d0cbcd2938 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed immutable graph/2 component decoder. Numeric graph/1 stays separate. */ +public final class WorldCanonicalAuthoredGraphReader { + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + + /** Complete original input supplies typed hierarchy/scope/Entity closure, never authority. */ + public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[] bytes) { + JsonNode root = JSON.readTree(bytes); + fields(root, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + text(root, "schemaVersion", "2"); + text(root, "canonicalTenantId", plan.graph().tenantId().toString()); + text(root, "canonicalVersionId", plan.graph().versionId().toString()); + JsonNode rows = root.get("rows"); + if (!rows.isArray() || rows.size() != plan.graph().nodes().size()) { + throw invalid("Missing or extra canonical graph rows"); + } + Map keys = new HashMap<>(); + Set privateKeys = new HashSet<>(); + Set mappingKeys = new HashSet<>(); + List decoded = new ArrayList<>(); + long tenant = 0; + long version = 0; + for (int i = 0; i < rows.size(); i++) { + JsonNode item = rows.get(i); + fields(item, Set.of("mapping", "content")); + JsonNode mapping = item.get("mapping"); + fields(mapping, MAPPING_FIELDS); + var node = plan.graph().nodes().get(i); + String family = WorldDraftTopologyCommitRepository.family(node); + var owner = plan.ownerBinding(); + text(mapping, "target_namespace", owner.targetNamespace()); + text(mapping, "canonical_tenant_id", plan.graph().tenantId().toString()); + text(mapping, "canonical_version_id", plan.graph().versionId().toString()); + text(mapping, "family", family); + text(mapping, "template_id", node.templateId().toString()); + text(mapping, "version_identity_operation_id", owner.versionIdentityOperationId().toString()); + text(mapping, "request_id", plan.binding().requestId().toString()); + text(mapping, "commit_id", plan.binding().commitId().toString()); + text(mapping, "revision_id", node.revisionId().toString()); + text(mapping, "revision_order", node.revisionOrder()); + long localTenant = positive(mapping, "tenant_id"); + long localVersion = positive(mapping, "version_id"); + if (i == 0) { + tenant = localTenant; + version = localVersion; + } + if (tenant != localTenant || version != localVersion) { + throw invalid("Canonical graph crosses private tenant or Version scope"); + } + long key = positive(mapping, "private_row_key"); + long mappingKey = positive(mapping, "id"); + if (keys.put(family + ":" + node.templateId(), key) != null + || !privateKeys.add(family + ":" + key) + || !mappingKeys.add(mappingKey)) { + throw invalid("Canonical graph mapping is not one-to-one within its typed family"); + } + decoded.add( + new Row( + new Template(Family.valueOf(family), node.templateId()), + mappingKey, + key, + node, + node.mutation())); + } + for (int i = 0; i < rows.size(); i++) { + JsonNode actual = rows.get(i).get("content"); + JsonNode expected = + JSON.valueToTree( + WorldDraftTopologyCommitRepository.expectedContent( + plan.graph().nodes().get(i), keys, tenant, version)); + if (!actual.isObject() || !WorldDraftTopologyCommitRepository.sameContent(actual, expected)) { + throw invalid("Canonical graph content differs from exact typed original payload"); + } + if (expected.properties().stream() + .anyMatch( + entry -> + entry.getValue().isIntegralNumber() + && !actual.get(entry.getKey()).isIntegralNumber())) { + throw invalid( + "Canonical graph private selectors and integer content require integer representation"); + } + Row original = decoded.get(i); + var content = original.authored().mutation().toBuilder(); + if (content.hasRegion()) { + content.setRegion( + content.getRegion().toBuilder() + .setSpacingMultiplier(actual.get("spacing_multiplier").doubleValue())); + } else if (content.hasRoomExit()) { + content.setRoomExit( + content.getRoomExit().toBuilder().setCost(actual.get("cost").intValue())); + } else if (content.hasWorldEntitySpawnBinding()) { + content.setWorldEntitySpawnBinding( + content.getWorldEntitySpawnBinding().toBuilder() + .setSpawnCount(actual.get("spawn_count").intValue())); + } + decoded.set( + i, + new Row( + original.template(), + original.mappingKey(), + original.privateRowKey(), + original.authored(), + content.build())); + } + return new WorldCanonicalAuthoredGraph( + plan.graph().tenantId(), plan.graph().versionId(), tenant, version, decoded); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null + || !node.isObject() + || node.size() != expected.size() + || node.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw invalid("Canonical graph has unsupported or missing fields"); + } + } + + private static void text(JsonNode node, String field, String expected) { + JsonNode actual = node.get(field); + if (actual == null || !actual.isString() || !actual.asText().equals(expected)) { + throw invalid("Canonical graph differs at " + field); + } + } + + private static long positive(JsonNode node, String field) { + JsonNode actual = node.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw invalid("Canonical graph requires a positive private integer at " + field); + } + return actual.longValue(); + } + + private static ConflictException invalid(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java new file mode 100644 index 0000000000..20ee3b41a1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; + +/** + * Immutable component capture, never Account authorization or complete participant/release proof. + */ +public final class WorldCanonicalFrozenTopology { + public static final String STATUS = "CAPTURED_UNVERIFIED"; + + public record Request(WorldDraftTopologyCommitPlan plan, CaptureRequest freeze) { + public Request { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(freeze, "freeze"); + var owner = plan.ownerBinding(); + if (!freeze.targetNamespace().equals(owner.targetNamespace()) + || !freeze.canonicalTenantId().equals(owner.canonicalTenantId()) + || !freeze.canonicalVersionId().equals(owner.canonicalVersionId()) + || !freeze.intakeRequestId().equals(owner.intakeRequestId()) + || !freeze.appliedCommitId().equals(plan.binding().commitId().toString())) { + throw new IllegalArgumentException( + "Frozen topology must bind the exact selected complete commit and source"); + } + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId()); + var expected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + if (expected.size() != freeze.suppliedOwnedAffectedTuples().size() + || !new java.util.HashSet<>(expected) + .equals(new java.util.HashSet<>(freeze.suppliedOwnedAffectedTuples()))) { + throw new IllegalArgumentException( + "Frozen topology must retain every exact original World affected tuple"); + } + } + } + + private final UUID captureId; + private final Request request; + private final WorldAuthoredVersionIdentityReceipt sourceIdentity; + private final WorldCanonicalAuthoredGraph graph; + private final byte[] graphBytes; + private final byte[] storageResultBytes; + private final byte[] resultBytes; + + WorldCanonicalFrozenTopology( + UUID captureId, + Request request, + WorldAuthoredVersionIdentityReceipt sourceIdentity, + WorldCanonicalAuthoredGraph graph, + byte[] graphBytes, + byte[] storageResultBytes, + byte[] resultBytes) { + this.captureId = Objects.requireNonNull(captureId, "captureId"); + if (captureId.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Capture ID must be non-nil"); + this.request = Objects.requireNonNull(request, "request"); + this.sourceIdentity = Objects.requireNonNull(sourceIdentity, "sourceIdentity"); + this.graph = Objects.requireNonNull(graph, "graph"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.storageResultBytes = + Objects.requireNonNull(storageResultBytes, "storageResultBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + } + + public UUID captureId() { + return captureId; + } + + public Request request() { + return request; + } + + public WorldAuthoredVersionIdentityReceipt sourceIdentity() { + return sourceIdentity; + } + + public WorldCanonicalAuthoredGraph graph() { + return graph; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] storageResultBytes() { + return storageResultBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java new file mode 100644 index 0000000000..3055518042 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Explicitly unwired immutable graph/2 journal; historical reads never reenter an owner writer. */ +public class WorldCanonicalFrozenTopologyRepository { + 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 DSLContext dsl; + private final WorldAuthoredGraphSnapshotRepository owner; + private final WorldDraftTopologyCommitRepository topology; + private final WorldDraftDesignDigestService digestService; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldCanonicalFrozenTopologyRepository( + DSLContext dsl, + WorldAuthoredGraphSnapshotRepository owner, + WorldDraftTopologyCommitRepository topology, + WorldDraftDesignDigestService digestService) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.owner = Objects.requireNonNull(owner, "owner"); + this.topology = Objects.requireNonNull(topology, "topology"); + this.digestService = Objects.requireNonNull(digestService, "digestService"); + } + + /** Absence is UNKNOWN, not abort or permission to reopen an owner operation. */ + public Optional readCommitted(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + return Optional.ofNullable(find(Objects.requireNonNull(request, "request"))); + } + + /** Complete publication selection; owner and original commit are reconstructed internally. */ + public Optional readCommitted(CaptureRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + return readFrozen(Objects.requireNonNull(request, "request")); + } + + /** Reads this immutable selector only inside the caller-owned read-only RR snapshot. */ + Optional readInOwnedSnapshot(CaptureRequest request) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readFrozen(Objects.requireNonNull(request, "request")); + } + + private Optional readFrozen(CaptureRequest request) { + Record row = + dsl.resultQuery( + "SELECT binding_json,binding_digest,owner_binding_json FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence()) + .fetchOne(); + if (row == null) return Optional.empty(); + var binding = + DraftCommitBinding.fromStored( + required(row, "binding_json", String.class), + required(row, "binding_digest", String.class)); + var ownerBinding = + JSON.readValue(required(row, "owner_binding_json", String.class), OwnerBinding.class); + return Optional.ofNullable( + find(new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), request))); + } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "Frozen topology snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(Connection::getTransactionIsolation); + if (!Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "Frozen topology snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } + + WorldCanonicalFrozenTopology capture(Request request) { + // This seam validates actual PostgreSQL isolation and serializes through the existing V25 row. + var provenance = owner.lockAndResolve(request.freeze()); + WorldCanonicalFrozenTopology prior = find(request); + if (prior != null) return prior; + if (request.freeze().digestSchemaVersion() != 3) { + throw new ConflictException("New canonical graph capture requires digest schema 3"); + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new ConflictException( + "New canonical graph capture requires the exact current FROZEN attempt"); + } + var stored = topology.readUnderFrozenLock(request.plan()); + Record original = + dsl.resultQuery( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json " + + "FROM world_authored_version_identity v JOIN world_authored_source_intake i " + + "ON i.operation_id=v.intake_operation_id WHERE v.operation_id=?", + request.plan().ownerBinding().versionIdentityOperationId()) + .fetchOne(); + if (original == null) + throw new ConflictException("Frozen topology has no exact original source identity"); + String identityJson = required(original, "identity_json", String.class); + String intakeJson = required(original, "intake_json", String.class); + var identity = topology.verifyOriginalSource(request.plan(), identityJson, intakeJson); + var graph = + topology.verifyImmutableBytes(request.plan(), stored.graphBytes(), stored.resultBytes()); + requirePrivateKeys(graph, identity); + var digest = + digestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(digest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(digest.scopeValue()) + || digest.digestSchemaVersion() != 3 + || !request.freeze().contentDigest().equals(digest.contentDigest())) { + throw new ConflictException( + "Canonical graph capture differs from exact schema-3 frozen content checkpoint"); + } + UUID captureId = UUID.randomUUID(); + String freezeJson = JSON.writeValueAsString(request.freeze()); + String ownerJson = JSON.writeValueAsString(request.plan().ownerBinding()); + byte[] result = + result( + captureId, + request, + identityJson, + intakeJson, + stored.graphBytes(), + stored.resultBytes()); + dsl.execute( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence," + + "request_id,commit_id,version_identity_operation_id,freeze_request_json,owner_binding_json," + + "binding_json,binding_digest,identity_json,intake_json,graph_bytes,graph_sha256," + + "storage_result_bytes,result_bytes,capture_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + captureId, + request.freeze().publicationFence(), + request.plan().binding().requestId(), + request.plan().binding().commitId(), + request.plan().ownerBinding().versionIdentityOperationId(), + freezeJson, + ownerJson, + request.plan().binding().canonicalJson(), + request.plan().binding().digest(), + identityJson, + intakeJson, + stored.graphBytes(), + WorldAuthoredGraphSnapshotCapture.sha256(stored.graphBytes()), + stored.resultBytes(), + result, + WorldCanonicalFrozenTopology.STATUS); + WorldCanonicalFrozenTopology readback = find(request); + if (readback == null + || !captureId.equals(readback.captureId()) + || !Arrays.equals(result, readback.resultBytes())) { + throw new ConflictException( + "Frozen topology differs from exact immutable insertion readback"); + } + return readback; + } + + private WorldCanonicalFrozenTopology find(Request supplied) { + Record row = + dsl.resultQuery( + "SELECT * FROM world_canonical_frozen_topology WHERE publication_fence=?", + supplied.freeze().publicationFence()) + .fetchOne(); + if (row == null) return null; + String bindingJson = required(row, "binding_json", String.class); + var binding = + DraftCommitBinding.fromStored(bindingJson, required(row, "binding_digest", String.class)); + String ownerJson = required(row, "owner_binding_json", String.class); + var ownerBinding = JSON.readValue(ownerJson, OwnerBinding.class); + String freezeJson = required(row, "freeze_request_json", String.class); + var freeze = JSON.readValue(freezeJson, CaptureRequest.class); + Request retained = + new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), freeze); + if (!binding.equals(supplied.plan().binding()) + || !ownerBinding.equals(supplied.plan().ownerBinding()) + || !freeze.equals(supplied.freeze()) + || !bindingJson.equals(binding.canonicalJson()) + || !ownerJson.equals(JSON.writeValueAsString(ownerBinding)) + || !freezeJson.equals(JSON.writeValueAsString(freeze))) { + throw new ConflictException( + "Frozen topology request was reused with changed complete input or checkpoint"); + } + UUID captureId = required(row, "capture_id", UUID.class); + if (!freeze.publicationFence().equals(required(row, "publication_fence", UUID.class)) + || !binding.requestId().equals(required(row, "request_id", UUID.class)) + || !binding.commitId().equals(required(row, "commit_id", UUID.class)) + || !ownerBinding + .versionIdentityOperationId() + .equals(required(row, "version_identity_operation_id", UUID.class)) + || !WorldCanonicalFrozenTopology.STATUS.equals( + required(row, "capture_status", String.class))) { + throw new ConflictException("Frozen topology journal identity or proof state differs"); + } + String identityJson = required(row, "identity_json", String.class); + String intakeJson = required(row, "intake_json", String.class); + JSON.readTree(identityJson); + JSON.readTree(intakeJson); + var identity = topology.verifyOriginalSource(retained.plan(), identityJson, intakeJson); + byte[] graphBytes = required(row, "graph_bytes", byte[].class); + byte[] storageResult = required(row, "storage_result_bytes", byte[].class); + if (!WorldAuthoredGraphSnapshotCapture.sha256(graphBytes) + .equals(required(row, "graph_sha256", String.class))) { + throw new ConflictException( + "Frozen canonical graph bytes failed immutable integrity readback"); + } + var graph = topology.verifyImmutableBytes(retained.plan(), graphBytes, storageResult); + requirePrivateKeys(graph, identity); + byte[] resultBytes = required(row, "result_bytes", byte[].class); + if (!Arrays.equals( + resultBytes, + result(captureId, retained, identityJson, intakeJson, graphBytes, storageResult))) { + throw new ConflictException( + "Frozen topology result differs from every original retained field"); + } + return new WorldCanonicalFrozenTopology( + captureId, retained, identity, graph, graphBytes, storageResult, resultBytes); + } + + private static void requirePrivateKeys( + WorldCanonicalAuthoredGraph graph, WorldAuthoredVersionIdentityReceipt identity) { + if (graph.localTenantKey() != identity.sourceIntakeReceipt().localTenantKey() + || graph.localVersionKey() != identity.localVersionKey()) { + throw new ConflictException( + "Canonical graph private keys differ from original source identity"); + } + } + + private byte[] result( + UUID id, + Request request, + String identityJson, + String intakeJson, + byte[] graph, + byte[] storageResult) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldCanonicalFrozenTopology.STATUS); + result.put( + "missingProof", + java.util.List.of( + "ACCOUNT_AUTHORIZATION", + "COMPLETE_PARTICIPANT_COMMIT", + "PUBLICATION_CHECKPOINT_DIGEST")); + result.put("captureId", id.toString()); + result.put("freeze", request.freeze()); + result.put("ownerBinding", request.plan().ownerBinding()); + result.put("bindingJson", request.plan().binding().canonicalJson()); + result.put("bindingDigest", request.plan().binding().digest()); + result.put("identityJson", identityJson); + result.put("intakeJson", intakeJson); + result.put("graphBytes", graph); + result.put("storageResultBytes", storageResult); + return JSON.writeValueAsBytes(result); + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) throw new ConflictException("Frozen topology is missing " + name); + return value; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java new file mode 100644 index 0000000000..3e8dceb9f2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-private, explicitly unwired capture; this adds no publication or runtime entry point. */ +public final class WorldCanonicalFrozenTopologyService { + private final WorldCanonicalFrozenTopologyRepository repository; + private final TransactionTemplate transaction; + + public WorldCanonicalFrozenTopologyService( + WorldCanonicalFrozenTopologyRepository repository, PlatformTransactionManager manager) { + this.repository = Objects.requireNonNull(repository, "repository"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** Exact retry reads the journal first, including after terminal state, without a writer. */ + public WorldCanonicalFrozenTopology capture(Request request) { + requireNoCallerTransaction(); + var prior = repository.readCommitted(request); + if (prior.isPresent()) return prior.orElseThrow(); + return Objects.requireNonNull(transaction.execute(status -> repository.capture(request))); + } + + public Optional readCommitted(Request request) { + requireNoCallerTransaction(); + return repository.readCommitted(request); + } + + private static void requireNoCallerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology requires an independent owner operation"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java new file mode 100644 index 0000000000..1148443f7f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Immutable component storage evidence; never Account permission, APPLIED, or fence release proof. + */ +public final class WorldDraftTopologyCommitEvidence { + public static final String STATUS = "STORED_PERMISSION_UNVERIFIED"; + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] graphBytes; + private final byte[] resultBytes; + + WorldDraftTopologyCommitEvidence( + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] graphBytes, + byte[] resultBytes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + if (graphBytes.length == 0 || resultBytes.length == 0) { + throw new IllegalArgumentException("Complete graph and storage result bytes are required"); + } + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java new file mode 100644 index 0000000000..2d15022849 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Pure UUID-qualified validation of complete fresh six-family World input: PURE_UNVERIFIED only. + * + *

This does not authenticate source or Entity evidence, authorize Account commits, allocate or + * read storage, report APPLIED, expose a public handler, capture released content, or establish + * lifecycle/runtime readiness. No selected-inbound, start-location or APPLIED authority is derived + * from this component. Free-text and localized JSON fields are preserved, not semantically + * validated. Zero spacing, exit cost and spawn count preserve the existing owner-default input + * convention; a future writer must apply those defaults without changing the original binding. + */ +public final class WorldDraftTopologyCommitPlan { + private static final ObjectMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final String TYPE_PREFIX = "WORLD_DESIGN_AGGREGATE_TYPE_"; + private static final String SCOPE_PREFIX = "WORLD_DESIGN_SCOPE_TYPE_"; + + private record ObjectReference(WorldDesignAggregateType kind, UUID templateId) {} + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final WorldDraftTopologyInputGraph graph; + + private WorldDraftTopologyCommitPlan( + DraftCommitBinding binding, OwnerBinding ownerBinding, WorldDraftTopologyInputGraph graph) { + this.binding = binding; + this.ownerBinding = ownerBinding; + this.graph = graph; + } + + /** + * Validates the exact supplied target and complete fresh input, without consulting any owner. All + * World references must close inside this graph; existing mappings are never guessed. + */ + public static WorldDraftTopologyCommitPlan create( + DraftCommitBinding binding, OwnerBinding ownerBinding) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + var target = binding.target(); + if (!target.canonicalTenantId().equals(ownerBinding.canonicalTenantId()) + || !target.canonicalVersionId().equals(ownerBinding.canonicalVersionId()) + || target.gameDesignVersionRowId() != ownerBinding.gameDesignVersionId() + || !"NEW_GAME_ROW".equals(target.sourceProvenanceKind())) { + throw invalid("Fresh World input differs from its supplied canonical target/source kind"); + } + + Map nodes = new LinkedHashMap<>(); + Set revisionIds = new HashSet<>(); + List expected = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + WorldDesignMutationRevision mutation = parse(revision.payload()); + if (!binding.commitId().toString().equals(mutation.getCommitId()) + || !revision.revisionId().toString().equals(mutation.getLogicalRevisionId()) + || !revisionIds.add(revision.revisionId())) { + throw invalid("World payload commit/revision identity differs from its complete input"); + } + validateShape(mutation); + UUID id = uuid(mutation.getAggregateId()); + UUID scope = uuid(mutation.getScopeId()); + EntityTemplateReference entity = null; + if (mutation.hasWorldEntitySpawnBinding()) { + var spawn = mutation.getWorldEntitySpawnBinding(); + entity = + new EntityTemplateReference( + spawn.getEntityTemplateType(), target.canonicalTenantId(), + target.canonicalVersionId(), uuid(spawn.getEntityTemplateId())); + } + Node node = + new Node(revision.revisionOrder(), revision.revisionId(), id, scope, mutation, entity); + if (nodes.putIfAbsent(new ObjectReference(mutation.getAggregateType(), id), node) != null) { + throw invalid("Fresh graph repeats an authored identity within the same World family"); + } + String type = mutation.getAggregateType().name().substring(TYPE_PREFIX.length()); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, type, id.toString(), "AGGREGATE", id.toString(), "0")); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + id.toString(), + mutation.getScopeType().name().substring(SCOPE_PREFIX.length()), + scope.toString(), + "0")); + } + if (nodes.isEmpty()) { + throw invalid("Fresh graph requires World input; an empty binding is not topology"); + } + validateClosure(nodes); + List actual = binding.affectedUnits(Owner.WORLD_MANAGEMENT); + if (actual.size() != expected.size() + || !new HashSet<>(actual).equals(new HashSet<>(expected))) { + throw invalid("World affected units omit or change a derived aggregate/containing scope"); + } + return new WorldDraftTopologyCommitPlan( + binding, + ownerBinding, + new WorldDraftTopologyInputGraph( + target.canonicalTenantId(), + target.canonicalVersionId(), + new ArrayList<>(nodes.values()))); + } + + /** Exact immutable enclosing binding, including other owners and original payload bytes. */ + public DraftCommitBinding binding() { + return binding; + } + + /** Supplied source-qualified binding, retained unchanged and still unauthenticated. */ + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + /** PURE_UNVERIFIED logical input only; no private row IDs or released snapshot. */ + public WorldDraftTopologyInputGraph graph() { + return graph; + } + + private static WorldDesignMutationRevision parse(String payload) { + try { + var parsed = STRICT_JSON.readTree(payload); + if (parsed == null || !parsed.isObject()) { + throw invalid("World typed payload must be an object"); + } + var builder = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(payload, builder); + return builder.build(); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalArgumentException("Unsupported World typed JSON", exception); + } catch (tools.jackson.core.JacksonException exception) { + throw new IllegalArgumentException( + "World typed JSON is not strict complete input", exception); + } + } + + private static void validateShape(WorldDesignMutationRevision m) { + if (m.getOperation() != WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT + || m.getScopeMutationPolicy() + != WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED + || (m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE + && m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + || m.getExpectedDraftRevisionEpoch() != 0 + || m.getExpectedDraftScopeRevisionEpoch() != 0) { + throw invalid( + "Fresh input supports scoped UPSERT with zero epochs and no replacement policy"); + } + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + require(m.hasRegion(), "REGION payload required"); + var p = m.getRegion(); + text(p.getName(), 100); + require( + p.getWeather().codePointCount(0, p.getWeather().length()) <= 50 + && p.getGeneratorType().codePointCount(0, p.getGeneratorType().length()) <= 50, + "Region weather/generator exceeds storage range"); + require( + p.getShardId() >= 0 + && Double.isFinite(p.getSpacingMultiplier()) + && p.getSpacingMultiplier() >= 0, + "Invalid region shard/spacing"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + require(m.hasZone(), "ZONE payload required"); + text(m.getZone().getName(), 100); + uuid(m.getZone().getRegionId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + require(m.hasRoom(), "ROOM payload required"); + text(m.getRoom().getName(), 100); + uuid(m.getRoom().getZoneId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + require(m.hasRoomExit(), "ROOM_EXIT payload required"); + var p = m.getRoomExit(); + uuid(p.getFromRoomId()); + uuid(p.getToRoomId()); + text(p.getDirection(), 32); + require(p.getCost() >= 0, "Exit cost must be nonnegative; zero retains the owner default"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + require(m.hasGenerationRule(), "GENERATION_RULE payload required"); + text(m.getGenerationRule().getName(), 100); + require( + m.getGenerationRule() + .getValue() + .codePointCount(0, m.getGenerationRule().getValue().length()) + <= 255, + "Rule value exceeds storage range"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + require(m.hasWorldEntitySpawnBinding(), "SPAWN payload required"); + var p = m.getWorldEntitySpawnBinding(); + uuid(p.getRoomId()); + uuid(p.getEntityTemplateId()); + require( + (p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + || p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + && p.getSpawnCount() >= 0 + && p.getRespawnDelaySeconds() >= 0, + "Invalid spawn type/count/delay"); + } + default -> + throw invalid("Unsupported fresh World family; generated subtrees are not full input"); + } + } + + private static void validateClosure(Map nodes) { + Map zoneRegions = new HashMap<>(); + Map roomZones = new HashMap<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + if (m.hasZone()) { + UUID region = uuid(m.getZone().getRegionId()); + parent(nodes, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION); + zoneRegions.put(node.templateId(), region); + } else if (m.hasRoom()) { + UUID zone = uuid(m.getRoom().getZoneId()); + parent(nodes, zone, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + roomZones.put(node.templateId(), zone); + } + } + Set> rules = new HashSet<>(); + Set> spawns = new HashSet<>(); + Set> exits = new HashSet<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + boolean regionScope = + m.getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE; + parent( + nodes, + node.scopeId(), + regionScope + ? WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + : WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> + require( + regionScope && node.templateId().equals(node.scopeId()), + "Region scope must be itself"); + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> + require( + regionScope + ? node.scopeId().equals(zoneRegions.get(node.templateId())) + : node.scopeId().equals(node.templateId()), + "Zone is outside declared scope"); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> + roomInScope(node.templateId(), node, roomZones, zoneRegions); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + UUID from = uuid(p.getFromRoomId()); + UUID to = uuid(p.getToRoomId()); + roomInScope(from, node, roomZones, zoneRegions); + roomInScope(to, node, roomZones, zoneRegions); + require( + exits.add(List.of(from.toString(), p.getDirection())), + "Duplicate room/direction exit"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> + require( + rules.add( + List.of( + m.getScopeType().name(), + node.scopeId().toString(), + m.getGenerationRule().getName())), + "Duplicate scoped generation rule"); + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + roomInScope(uuid(p.getRoomId()), node, roomZones, zoneRegions); + require( + spawns.add( + List.of( + p.getRoomId(), p.getEntityTemplateType().name(), p.getEntityTemplateId())), + "Duplicate typed room/entity spawn binding"); + } + default -> throw invalid("Unsupported World family"); + } + } + } + + private static void roomInScope( + UUID room, Node node, Map rooms, Map zones) { + UUID zone = rooms.get(room); + require(zone != null, "Room reference is not in the complete fresh graph"); + UUID containing = + node.mutation().getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE + ? zone + : zones.get(zone); + require(node.scopeId().equals(containing), "Room or exit endpoint is outside declared scope"); + } + + private static void parent( + Map nodes, UUID id, WorldDesignAggregateType type) { + Node node = nodes.get(new ObjectReference(type, id)); + require(node != null, "Missing or wrong-family reference in complete fresh graph"); + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + require( + id.toString().equals(value) && !id.equals(new UUID(0, 0)), + "World logical IDs require canonical non-nil UUIDs"); + return id; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "World logical IDs require canonical non-nil UUIDs", exception); + } + } + + private static void text(String value, int maximum) { + require( + !value.isBlank() && value.codePointCount(0, value.length()) <= maximum, + "Required World text is blank or exceeds storage range"); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw invalid(message); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java new file mode 100644 index 0000000000..c7702ff47c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -0,0 +1,617 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Actual guarded six-family component storage; explicitly unwired, with private keys. */ +public class WorldDraftTopologyCommitRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final ObjectMapper mapper; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldDraftTopologyCommitRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + } + + /** Independent committed reconciliation: absence is UNKNOWN, never definitive abort. */ + public Optional readCommitted( + WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + } + + /** Caller already holds the exact shared V25 FROZEN owner lock; no writer is entered. */ + WorldDraftTopologyCommitEvidence readUnderFrozenLock(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + WorldDraftTopologyCommitEvidence stored = + find(plan, mapper.writeValueAsString(plan.ownerBinding())); + if (stored == null) { + throw new ConflictException("World frozen capture has no committed complete topology result"); + } + return stored; + } + + /** Validates historical bytes without consulting current content, epochs or owner phase. */ + WorldCanonicalAuthoredGraph verifyImmutableBytes( + WorldDraftTopologyCommitPlan plan, byte[] graph, byte[] result) { + WorldCanonicalAuthoredGraph decoded = new WorldCanonicalAuthoredGraphReader().read(plan, graph); + if (!Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World historical topology result differs from original input"); + } + return decoded; + } + + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + WorldDraftTopologyCommitEvidence prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + OpenOwner owner = fence.lockOpenAndResolve(plan.ownerBinding()); + var source = owner.receipt().source(); + var target = plan.binding().target(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new ConflictException("World topology differs from retained intake source provenance"); + } + // Reconcile again after the shared OPEN/freeze lock: an exact first claimant may have won. + prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + dsl.resultQuery( + "SELECT world_store_guarded_uuid_topology(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + mapper.writeValueAsString(executionRevisions(plan))) + .fetch(); + byte[] graph = readAndVerifyGraph(plan, owner.localTenantKey(), owner.localVersionKey()); + byte[] result = encodeResult(plan, graph); + dsl.execute( + "INSERT INTO world_topology_draft_commit (request_id,commit_id,version_identity_operation_id," + + "target_namespace,canonical_tenant_id,canonical_version_id,local_tenant_key,local_version_key," + + "owner_binding_json,binding_json,binding_digest,graph_bytes,graph_sha256,result_bytes,storage_status) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + plan.ownerBinding().targetNamespace(), + target.canonicalTenantId(), + target.canonicalVersionId(), + owner.localTenantKey(), + owner.localVersionKey(), + ownerJson, + plan.binding().canonicalJson(), + plan.binding().digest(), + graph, + sha256(graph), + result, + WorldDraftTopologyCommitEvidence.STATUS); + return new WorldDraftTopologyCommitEvidence(plan.binding(), plan.ownerBinding(), graph, result); + } + + /** + * Trusted local typed projection, like V29's typed component changes. The complete original + * binding remains unchanged. SQL checks revision identities/order/owner; before storing history, + * actual rows are independently checked against the original parsed plan, so altered projected + * semantics roll back the complete transaction. This is never an input from a public caller. + */ + List executionRevisions(WorldDraftTopologyCommitPlan plan) { + List revisions = new ArrayList<>(); + for (Node node : plan.graph().nodes()) { + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + node.revisionOrder(), + node.revisionId(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(node.mutation()))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "World typed execution projection could not be encoded", exception); + } + } + return List.copyOf(revisions); + } + + private WorldDraftTopologyCommitEvidence find( + WorldDraftTopologyCommitPlan plan, String ownerJson) { + List records = + dsl.resultQuery( + "SELECT c.*, to_jsonb(v)::text AS identity_json, " + + "to_jsonb(i)::text AS intake_json FROM world_topology_draft_commit c " + + "JOIN world_authored_version_identity v ON v.operation_id=c.version_identity_operation_id " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id " + + "WHERE c.request_id=? OR c.commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()) + .fetch(); + if (records.isEmpty()) { + return null; + } + if (records.size() != 1) { + throw new ConflictException("World complete request and commit select conflicting history"); + } + Record row = records.getFirst(); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + if (!binding.equals(plan.binding()) + || !ownerJson.equals(row.get("owner_binding_json", String.class))) { + throw new ConflictException( + "World complete request or commit was reused with changed full input or source"); + } + WorldAuthoredVersionIdentityReceipt original = + verifyOriginalSource( + plan, row.get("identity_json", String.class), row.get("intake_json", String.class)); + long tenant = original.sourceIntakeReceipt().localTenantKey(); + long version = original.localVersionKey(); + var o = plan.ownerBinding(); + if (tenant <= 0 + || version <= 0 + || !Objects.equals(row.get("request_id", UUID.class), binding.requestId()) + || !Objects.equals(row.get("commit_id", UUID.class), binding.commitId()) + || !Objects.equals(row.get("target_namespace", String.class), o.targetNamespace()) + || !Objects.equals(row.get("canonical_tenant_id", UUID.class), o.canonicalTenantId()) + || !Objects.equals(row.get("canonical_version_id", UUID.class), o.canonicalVersionId()) + || !Objects.equals(row.get("local_tenant_key", Long.class), tenant) + || !Objects.equals(row.get("local_version_key", Long.class), version) + || !WorldDraftTopologyCommitEvidence.STATUS.equals( + row.get("storage_status", String.class))) { + throw new ConflictException("World immutable topology identity provenance is inconsistent"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + byte[] result = row.get("result_bytes", byte[].class); + if (!sha256(graph).equals(row.get("graph_sha256", String.class)) + || !Arrays.equals(graph, readAndVerifyGraph(plan, tenant, version)) + || !Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World immutable topology payload, graph or result differs"); + } + return new WorldDraftTopologyCommitEvidence(binding, o, graph, result); + } + + /** Reuses the original closed source and Version evidence validators for detached history. */ + WorldAuthoredVersionIdentityReceipt verifyOriginalSource( + WorldDraftTopologyCommitPlan plan, String identityJson, String intakeJson) { + DraftCommitBinding binding = plan.binding(); + JsonNode identity = mapper.readTree(identityJson); + JsonNode intake = mapper.readTree(intakeJson); + var o = plan.ownerBinding(); + requireField(identity, "operation_id", o.versionIdentityOperationId()); + requireField(identity, "target_namespace", o.targetNamespace()); + requireField(identity, "canonical_tenant_id", o.canonicalTenantId()); + requireField(identity, "canonical_version_id", o.canonicalVersionId()); + requireField(identity, "game_design_version_id", o.gameDesignVersionId()); + requireField(identity, "intake_operation_id", o.intakeOperationId()); + requireField(identity, "intake_request_id", o.intakeRequestId()); + requireField(identity, "intake_request_digest", o.intakeRequestDigest()); + requireField(identity, "source_operation_id", o.sourceOperationId()); + requireField(identity, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(identity, "intake_receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "operation_id", o.intakeOperationId()); + requireField(intake, "intake_request_id", o.intakeRequestId()); + requireField(intake, "target_namespace", o.targetNamespace()); + requireField(intake, "canonical_tenant_id", o.canonicalTenantId()); + requireField(intake, "request_digest", o.intakeRequestDigest()); + requireField(intake, "source_operation_id", o.sourceOperationId()); + requireField(intake, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(intake, "receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "source_game_row_id", binding.target().sourceGameRowId()); + requireField(intake, "source_game_tenant_key", binding.target().sourceGameTenantKey()); + requireField(intake, "source_provenance_kind", binding.target().sourceProvenanceKind()); + long tenant = identity.path("local_tenant_key").asLong(); + long version = identity.path("local_version_key").asLong(); + requireField(intake, "local_tenant_key", tenant); + // Reuse the existing closed source/receipt validators; these are original local evidence, + // not a current upstream Version or permission check. + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + intake.path("source_schema_version").asInt(), + o.targetNamespace(), + UUID.fromString(intake.path("source_registration_request_id").asText()), + o.sourceOperationId(), + intake.path("source_request_digest").asText(), + o.canonicalTenantId(), + intake.path("tenant_slug").asText(), + intake.path("world_slug").asText(), + intake.path("world_display_name").asText(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + o.sourceEvidenceDigest()); + WorldAuthoredSourceIntakeReceipt receipt = + new WorldAuthoredSourceIntakeReceipt( + intake.path("schema_version").asInt(), + o.targetNamespace(), + o.intakeRequestId(), + o.intakeOperationId(), + o.canonicalTenantId(), + source.worldSlug(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeRequestDigest(), + o.intakeReceiptDigest(), + tenant, + source); + AuthoredWorldVersionStateEvidence state = + mapper.readValue( + identity.path("version_state_evidence_json").asText(), + AuthoredWorldVersionStateEvidence.class); + WorldAuthoredVersionIdentityReceipt retainedIdentity = + new WorldAuthoredVersionIdentityReceipt( + 1, o.versionIdentityOperationId(), version, receipt, state); + requireField(identity, "version_state_schema_version", state.request().schemaVersion()); + requireField(identity, "version_state_read_request_id", state.request().readRequestId()); + requireField(identity, "version_state_epoch", state.versionStateEpoch()); + requireField(identity, "version_state_evidence_digest", state.evidenceDigest()); + requireField( + identity, + "version_state_state", + state.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")); + requireField(identity, "world_slug", source.worldSlug()); + if (!retainedIdentity.canonicalVersionId().equals(o.canonicalVersionId()) + || retainedIdentity.gameDesignVersionId() != o.gameDesignVersionId()) { + throw new ConflictException( + "World topology differs from retained closed Version/source evidence"); + } + return retainedIdentity; + } + + private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant, long version) { + // Graph/2 and graph/3 retain their original fourteen mapping fields. Private fixture + // metadata is checked separately through JSON so pre-fixture schemas remain readable. + List mappings = + dsl.resultQuery( + "SELECT jsonb_build_object(" + + "'id',m.id,'target_namespace',m.target_namespace," + + "'canonical_tenant_id',m.canonical_tenant_id," + + "'canonical_version_id',m.canonical_version_id,'family',m.family," + + "'template_id',m.template_id,'private_row_key',m.private_row_key," + + "'tenant_id',m.tenant_id,'version_id',m.version_id," + + "'version_identity_operation_id',m.version_identity_operation_id," + + "'request_id',m.request_id,'commit_id',m.commit_id," + + "'revision_id',m.revision_id,'revision_order',m.revision_order)" + + "::text AS mapping_json," + + "to_jsonb(m)->>'preparation_authority_kind' AS preparation_authority_kind," + + "to_jsonb(m)->>'fixture_provenance_digest' AS fixture_provenance_digest," + + "to_jsonb(m)->>'fixture_world_instance_id' AS fixture_world_instance_id," + + "to_jsonb(m)->>'fixture_operation_id' AS fixture_operation_id " + + "FROM world_authored_topology_identity m " + + "WHERE m.request_id=? ORDER BY m.revision_order::numeric", + plan.binding().requestId()) + .fetch(); + if (mappings.size() != plan.graph().nodes().size()) { + throw new ConflictException("World topology has missing or extra exact UUID mappings"); + } + for (var type : + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING")) { + long expected = plan.graph().nodes().stream().filter(n -> family(n).equals(type)).count(); + Long actual = + dsl.resultQuery( + "SELECT count(*) FROM " + + type.toLowerCase(java.util.Locale.ROOT) + + " WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(actual, expected)) { + throw new ConflictException( + "World topology contains extra or missing actual " + + type.toLowerCase(java.util.Locale.ROOT) + + " rows"); + } + } + Map keys = new HashMap<>(); + List identities = new ArrayList<>(); + for (int i = 0; i < mappings.size(); i++) { + Node node = plan.graph().nodes().get(i); + Record mapping = mappings.get(i); + String authority = mapping.get("preparation_authority_kind", String.class); + if ((authority != null && !"HUMAN".equals(authority)) + || mapping.get("fixture_provenance_digest", String.class) != null + || mapping.get("fixture_world_instance_id", String.class) != null + || mapping.get("fixture_operation_id", String.class) != null) { + throw new ConflictException( + "Human topology mapping carries fixture authority or provenance"); + } + JsonNode m = mapper.readTree(mapping.get("mapping_json", String.class)); + String family = family(node); + requireField(m, "target_namespace", plan.ownerBinding().targetNamespace()); + requireField(m, "canonical_tenant_id", plan.graph().tenantId()); + requireField(m, "canonical_version_id", plan.graph().versionId()); + requireField(m, "family", family); + requireField(m, "template_id", node.templateId()); + requireField(m, "tenant_id", tenant); + requireField(m, "version_id", version); + requireField( + m, "version_identity_operation_id", plan.ownerBinding().versionIdentityOperationId()); + requireField(m, "request_id", plan.binding().requestId()); + requireField(m, "commit_id", plan.binding().commitId()); + requireField(m, "revision_id", node.revisionId()); + requireField(m, "revision_order", node.revisionOrder()); + long key = m.path("private_row_key").asLong(); + if (key <= 0 + || m.path("id").asLong() <= 0 + || keys.put(family + ":" + node.templateId(), key) != null) { + throw new ConflictException("World UUID mapping is not one-to-one"); + } + identities.add(m); + } + List> rows = new ArrayList<>(); + for (int i = 0; i < identities.size(); i++) { + Node node = plan.graph().nodes().get(i); + String family = family(node); + long key = keys.get(family + ":" + node.templateId()); + // The table name is selected only from the closed protobuf family enumeration. + Record row = + dsl.resultQuery( + "SELECT to_jsonb(t)::text AS content_json FROM " + + family.toLowerCase(java.util.Locale.ROOT) + + " t WHERE id=?", + key) + .fetchOne(); + if (row == null) { + throw new ConflictException("World UUID association has no actual allocated row"); + } + JsonNode actual = mapper.readTree(row.get("content_json", String.class)); + JsonNode expected = mapper.valueToTree(expectedContent(node, keys, tenant, version)); + if (!sameContent(actual, expected)) { + throw new ConflictException("World allocated row differs from every exact payload field"); + } + Map item = new LinkedHashMap<>(); + item.put("mapping", identities.get(i)); + item.put("content", actual); + rows.add(item); + } + for (Node node : plan.graph().nodes()) { + Long epoch = + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=? AND aggregate_type=? AND aggregate_id=?", + tenant, + version, + family(node), + keys.get(family(node) + ":" + node.templateId())) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology aggregate epoch differs from exact stored result"); + } + } + Long aggregateCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + long scopeCountExpected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .filter(u -> !u.scopeType().equals("AGGREGATE")) + .map(u -> u.scopeType() + ":" + u.scopeId()) + .distinct() + .count(); + Long scopeCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(aggregateCount, (long) plan.graph().nodes().size()) + || !Objects.equals(scopeCount, scopeCountExpected)) { + throw new ConflictException("World topology has extra or missing exact epoch fences"); + } + for (var unit : plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT)) { + if (!unit.scopeType().equals("AGGREGATE")) { + Long epoch = + dsl.resultQuery( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=? AND scope_type=? AND scope_id=?", + tenant, + version, + unit.scopeType(), + unit.scopeId()) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology scope epoch differs from exact stored result"); + } + } + } + Map graph = new LinkedHashMap<>(); + graph.put("schemaVersion", "2"); + graph.put("canonicalTenantId", plan.graph().tenantId().toString()); + graph.put("canonicalVersionId", plan.graph().versionId().toString()); + graph.put("rows", rows); + return mapper.writeValueAsBytes(graph); + } + + static Map expectedContent( + Node node, Map keys, long tenant, long version) { + Map row = new LinkedHashMap<>(); + var m = node.mutation(); + row.put("id", keys.get(family(node) + ":" + node.templateId())); + row.put("tenant_id", tenant); + row.put("version_id", version); + row.put("version", 0); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + var p = m.getRegion(); + row.put("name", p.getName()); + row.put("shard_id", p.getShardId()); + row.put("weather", p.getWeather()); + row.put("generation_seed", p.getGenerationSeed()); + row.put("generator_type", p.getGeneratorType()); + row.put("generator_params", p.getGeneratorParams()); + row.put( + "spacing_multiplier", p.getSpacingMultiplier() == 0 ? 1.0 : p.getSpacingMultiplier()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + row.put("name", m.getZone().getName()); + row.put("region_id", lookup(keys, "REGION", m.getZone().getRegionId())); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + var p = m.getRoom(); + row.put("name", p.getName()); + row.put("description", p.getDescription()); + row.put("zone_id", lookup(keys, "ZONE", p.getZoneId())); + row.put("name_localized_variants_json", p.getNameLocalizedVariantsJson()); + row.put("description_localized_variants_json", p.getDescriptionLocalizedVariantsJson()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + row.put("from_room_id", lookup(keys, "ROOM", p.getFromRoomId())); + row.put("to_room_id", lookup(keys, "ROOM", p.getToRoomId())); + row.put("direction", p.getDirection()); + row.put("cost", p.getCost() == 0 ? 1 : p.getCost()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + var p = m.getGenerationRule(); + row.put("name", p.getName()); + row.put("value", p.getValue()); + String scope = m.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""); + row.put("scope_type", scope); + row.put( + "scope_id", + lookup( + keys, + scope.equals("REGION_SUBTREE") ? "REGION" : "ZONE", + node.scopeId().toString()) + .toString()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + var e = node.entityReference(); + row.put("room_id", lookup(keys, "ROOM", p.getRoomId())); + row.put( + "entity_template_type", e.kind().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", "")); + row.put("entity_template_id", null); + row.put("entity_canonical_tenant_id", e.tenantId().toString()); + row.put("entity_canonical_version_id", e.versionId().toString()); + row.put("entity_canonical_template_id", e.templateId().toString()); + row.put("spawn_count", p.getSpawnCount() == 0 ? 1 : p.getSpawnCount()); + row.put("respawn_delay_seconds", p.getRespawnDelaySeconds()); + } + default -> throw new ConflictException("Unsupported exact World family"); + } + return row; + } + + private static Long lookup(Map keys, String family, String id) { + return Objects.requireNonNull( + keys.get(family + ":" + UUID.fromString(id)), "typed parent mapping"); + } + + static String family(Node node) { + return node.mutation().getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + } + + private void requireField(JsonNode node, String name, Object expected) { + if (!node.hasNonNull(name) || !node.path(name).asText().equals(expected.toString())) { + throw new ConflictException("World immutable topology provenance differs at " + name); + } + } + + static boolean sameContent(JsonNode actual, JsonNode expected) { + if (actual.size() != expected.size()) { + return false; + } + for (var entry : expected.properties()) { + JsonNode value = actual.get(entry.getKey()); + JsonNode required = entry.getValue(); + if (value == null + || (value.isNumber() && required.isNumber() + ? value.decimalValue().compareTo(required.decimalValue()) != 0 + : !value.equals(required))) { + return false; + } + } + return true; + } + + private byte[] encodeResult(WorldDraftTopologyCommitPlan plan, byte[] graph) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "2"); + result.put("status", WorldDraftTopologyCommitEvidence.STATUS); + result.put("requestId", plan.binding().requestId().toString()); + result.put("commitId", plan.binding().commitId().toString()); + result.put("bindingDigest", plan.binding().digest()); + result.put("ownerBinding", plan.ownerBinding()); + result.put("graphSha256", sha256(graph)); + result.put( + "affectedEpochsAfter", + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", u.aggregateType()); + after.put("aggregateId", u.aggregateId()); + after.put("scopeType", u.scopeType()); + after.put("scopeId", u.scopeId()); + after.put("epoch", "1"); + return after; + }) + .toList()); + return mapper.writeValueAsBytes(result); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + java.sql.Connection.TRANSACTION_READ_COMMITTED)) { + throw new ConflictException( + "World complete storage requires writable READ COMMITTED transaction"); + } + } + + private String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java new file mode 100644 index 0000000000..e22f69c59d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** + * Immutable PURE_UNVERIFIED logical input, never a stored or released World graph. + * + *

No numeric allocation, source authentication, Account authorization, APPLIED result, + * synchronized visibility, public handler, lifecycle or runtime readiness follows from this value. + * Its protobuf values preserve every supplied payload field without normalizing defaults. + * Preserving free-text and localized JSON fields does not validate their semantics. + */ +public final class WorldDraftTopologyInputGraph { + public static final String STATUS = "PURE_UNVERIFIED"; + + /** A typed canonical Entity reference; existence and owner authority remain unverified. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(templateId, "templateId"); + } + } + + /** One complete immutable logical mutation in its original enclosing revision position. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value messages.") + public record Node( + String revisionOrder, + UUID revisionId, + UUID templateId, + UUID scopeId, + WorldDesignMutationRevision mutation, + EntityTemplateReference entityReference) { + public Node { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(templateId, "templateId"); + Objects.requireNonNull(scopeId, "scopeId"); + Objects.requireNonNull(mutation, "mutation"); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final List nodes; + + WorldDraftTopologyInputGraph(UUID tenantId, UUID versionId, List nodes) { + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.versionId = Objects.requireNonNull(versionId, "versionId"); + this.nodes = List.copyOf(nodes); + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + /** All six families in original canonical revision order, including interleaved families. */ + public List nodes() { + return nodes; + } + + /** An immutable family view retaining original order; an empty family is not readiness proof. */ + public List family(WorldDesignAggregateType kind) { + Objects.requireNonNull(kind, "kind"); + return nodes.stream().filter(node -> node.mutation().getAggregateType() == kind).toList(); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql b/services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql new file mode 100644 index 0000000000..87e2e426cf --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql @@ -0,0 +1,264 @@ +-- Graph-snapshot additions on the canonical V27.1 publication-owner binding. +-- V27.1 already owns the attempt tuple, owner columns, closed check and exact foreign key; +-- preserve those immutable parent definitions and add only the missing snapshot capability. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD CONSTRAINT uq_world_publication_snapshot_binding UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ); + +CREATE TABLE world_authored_graph_snapshot ( + snapshot_id UUID NOT NULL, + capture_request_digest VARCHAR(64) NOT NULL, + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + owner_binding_schema_version SMALLINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + supplied_owned_affected_tuples_json TEXT NOT NULL, + owner_revision_evidence_json TEXT NOT NULL, + owner_commit_proof_status VARCHAR(32) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_world_authored_graph_snapshot PRIMARY KEY (snapshot_id), + CONSTRAINT uq_world_authored_graph_snapshot_fence UNIQUE (publication_fence), + CONSTRAINT uq_world_authored_graph_snapshot_request UNIQUE ( + target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id + ), + CONSTRAINT fk_world_authored_graph_snapshot_attempt FOREIGN KEY ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + local_version_key, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ) REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ), + CONSTRAINT fk_world_authored_graph_snapshot_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ), + CONSTRAINT fk_world_authored_graph_snapshot_intake FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version = 2 + ), + CONSTRAINT ck_world_authored_graph_snapshot_ids CHECK ( + snapshot_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_graph_snapshot_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_source_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_request CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND capture_request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + ), + CONSTRAINT ck_world_authored_graph_snapshot_checkpoint CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 + ), + CONSTRAINT ck_world_authored_graph_snapshot_proof CHECK ( + owner_commit_proof_status = 'CAPTURED_UNVERIFIED' + AND octet_length(supplied_owned_affected_tuples_json) > 0 + AND octet_length(owner_revision_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_authored_graph_snapshot_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored graph snapshot history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_authored_graph_snapshot_immutable + BEFORE UPDATE OR DELETE ON world_authored_graph_snapshot + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); + +CREATE TRIGGER trg_world_authored_graph_snapshot_no_truncate + BEFORE TRUNCATE ON world_authored_graph_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql b/services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql new file mode 100644 index 0000000000..1cfada70b8 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql @@ -0,0 +1,392 @@ +-- Complete owner-local component storage only: no Account permission or publication proof. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_region_commit_identity UNIQUE ( + operation_id, target_namespace, canonical_tenant_id, canonical_version_id, local_version_key + ); + +CREATE TABLE world_region_draft_commit ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + result_bytes BYTEA NOT NULL, + storage_status VARCHAR(32) NOT NULL, + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_region_commit_identity FOREIGN KEY ( + version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ), + CONSTRAINT ck_world_region_commit_evidence CHECK ( + binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 AND octet_length(result_bytes) > 0 + AND storage_status = 'STORED_PERMISSION_UNVERIFIED' + AND local_tenant_key > 0 AND local_version_key > 0 + ) +); + +-- The function below creates and consumes these exact row transitions within its execution. +-- No manifest survives the function, and ordinary application code never inserts one. +CREATE TABLE world_region_draft_execution_manifest ( + transaction_id BIGINT NOT NULL, + operation_id UUID NOT NULL, + table_name VARCHAR(50) NOT NULL, + row_id BIGINT NOT NULL, + row_operation TEXT NOT NULL, + version_identity_operation_id UUID NOT NULL REFERENCES world_authored_version_identity(operation_id), + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding JSONB NOT NULL, + complete_binding JSONB NOT NULL, + expected_old JSONB, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, operation_id, table_name, row_id), + CHECK (table_name IN ('region', 'world_design_aggregate_epoch', 'world_design_scope_epoch')), + CHECK (row_operation IN ('INSERT', 'UPDATE')), + CHECK ((row_operation = 'INSERT' AND expected_old IS NULL AND table_name <> 'region') + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL)) +); + +-- [jooq ignore start] +REVOKE ALL ON world_region_draft_execution_manifest FROM PUBLIC; + +CREATE TRIGGER trg_world_region_commit_immutable + BEFORE UPDATE OR DELETE ON world_region_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_region_commit_no_truncate + BEFORE TRUNCATE ON world_region_draft_commit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_consume_region_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation NOT IN ('INSERT', 'UPDATE') OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_region_draft_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_design_publication_fence_owner o + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table AND m.row_operation = actual_operation + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NOT DISTINCT FROM actual_old + AND m.expected_new = actual_new + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.local_version_key = (actual_new->>'version_id')::BIGINT + AND v.operation_id = m.version_identity_operation_id + AND v.local_tenant_key = m.local_tenant_key + AND v.local_version_key = m.local_version_key + AND v.operation_id::TEXT = m.owner_binding->>'versionIdentityOperationId' + AND v.target_namespace = m.owner_binding->>'targetNamespace' + AND v.canonical_tenant_id::TEXT = m.owner_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.owner_binding->>'canonicalVersionId' + AND v.intake_operation_id::TEXT = m.owner_binding->>'intakeOperationId' + AND v.intake_request_id::TEXT = m.owner_binding->>'intakeRequestId' + AND v.intake_request_digest = m.owner_binding->>'intakeRequestDigest' + AND v.source_operation_id::TEXT = m.owner_binding->>'sourceOperationId' + AND v.source_evidence_digest = m.owner_binding->>'sourceEvidenceDigest' + AND v.intake_receipt_digest = m.owner_binding->>'intakeReceiptDigest' + AND v.game_design_version_id = (m.owner_binding->>'gameDesignVersionId')::BIGINT + AND v.canonical_tenant_id::TEXT = m.complete_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.complete_binding->>'canonicalVersionId' + AND m.operation_id::TEXT = m.complete_binding->>'commitId' + AND o.target_namespace = v.target_namespace + AND o.canonical_tenant_id = v.canonical_tenant_id + AND o.local_tenant_key = v.local_tenant_key AND o.version_id = v.local_version_key + AND o.owner_freeze_phase = 'OPEN' AND o.current_publication_fence IS NULL + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_region_execution_manifest(TEXT, TEXT, JSONB, JSONB) FROM PUBLIC; + +-- Retain the V24 deny boundary everywhere except an exact, single-use transition created by +-- the dedicated function. Moving a row out of a canonical tenant still enters this branch. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest(TG_TABLE_NAME, TG_OP, old_row, new_row) + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +-- p_changes is the trusted component's typed, independently scope-validated complete World +-- subset. It grants no permission. Its tuples are rechecked against the retained full binding. +-- Neither a tenant allowlist nor a session flag can enable a guarded row write. +CREATE FUNCTION world_store_guarded_region_rows(p_owner JSONB, p_binding JSONB, p_changes JSONB) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + old_region "${serviceSchema}".region%ROWTYPE; + new_region "${serviceSchema}".region%ROWTYPE; + old_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + new_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + old_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + new_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + change JSONB; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_aggregate BIGINT; + expected_scope BIGINT; + aggregate_exists BOOLEAN; + scope_exists BOOLEAN; + affected INTEGER; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR jsonb_typeof(p_changes) <> 'array' OR jsonb_array_length(p_changes) = 0 + THEN + RAISE EXCEPTION 'Complete World region storage requires writable READ COMMITTED input' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World region storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(DISTINCT value->>'id') FROM jsonb_array_elements(p_changes)) + <> jsonb_array_length(p_changes) THEN + RAISE EXCEPTION 'World complete region storage has duplicate region targets' + USING ERRCODE = '23514'; + END IF; + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'AGGREGATE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedAggregateEpoch'), + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'REGION_SUBTREE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedScopeEpoch')); + END LOOP; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType'), '[]'::JSONB) + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType') + INTO expected_units FROM jsonb_array_elements(expected_units); + IF supplied_units IS DISTINCT FROM expected_units THEN + RAISE EXCEPTION 'World complete storage requires every exact REGION and REGION_SUBTREE tuple' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_changes) + WHERE (value->>'expectedAggregateEpoch')::BIGINT < 0 + OR (value->>'expectedAggregateEpoch')::BIGINT = 9223372036854775807 + OR (value->>'expectedScopeEpoch')::BIGINT < 0 + OR (value->>'expectedScopeEpoch')::BIGINT = 9223372036854775807) THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_aggregate := (change->>'expectedAggregateEpoch')::BIGINT; + expected_scope := (change->>'expectedScopeEpoch')::BIGINT; + IF expected_aggregate < 0 OR expected_aggregate = 9223372036854775807 + OR expected_scope < 0 OR expected_scope = 9223372036854775807 THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT old_region FROM "${serviceSchema}".region + WHERE id = (change->>'id')::BIGINT AND tenant_id = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + new_region := old_region; + new_region.name := change->>'name'; + new_region.shard_id := (change->>'shardId')::INTEGER; + new_region.weather := change->>'weather'; + new_region.generation_seed := (change->>'generationSeed')::BIGINT; + new_region.generator_type := change->>'generatorType'; + new_region.generator_params := change->>'generatorParams'; + new_region.spacing_multiplier := (change->>'spacingMultiplier')::DOUBLE PRECISION; + IF new_region.name IS NULL OR btrim(new_region.name) = '' OR new_region.shard_id < 0 + OR new_region.spacing_multiplier <= 0 + OR new_region.spacing_multiplier IN ('NaN'::DOUBLE PRECISION, 'Infinity'::DOUBLE PRECISION) THEN + RAISE EXCEPTION 'World region payload is invalid' USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'region', old_region.id, 'UPDATE', + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, to_jsonb(old_region), to_jsonb(new_region)); + UPDATE "${serviceSchema}".region SET name = new_region.name, shard_id = new_region.shard_id, + weather = new_region.weather, generation_seed = new_region.generation_seed, + generator_type = new_region.generator_type, generator_params = new_region.generator_params, + spacing_multiplier = new_region.spacing_multiplier + WHERE id = old_region.id AND to_jsonb(region) = to_jsonb(old_region); + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'World region changed during complete storage' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_aggregate FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND aggregate_type = 'REGION' AND aggregate_id = old_region.id FOR UPDATE; + aggregate_exists := FOUND; + IF (aggregate_exists AND old_aggregate.draft_revision_epoch <> expected_aggregate) + OR (NOT aggregate_exists AND expected_aggregate <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate epoch' USING ERRCODE = '23514'; + END IF; + IF aggregate_exists THEN + new_aggregate := old_aggregate; + ELSE + new_aggregate.id := nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'); + new_aggregate.tenant_id := identity_row.local_tenant_key; + new_aggregate.version_id := identity_row.local_version_key; + new_aggregate.aggregate_type := 'REGION'; + new_aggregate.aggregate_id := old_region.id; + END IF; + new_aggregate.draft_revision_epoch := expected_aggregate + 1; + new_aggregate.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_aggregate_epoch', new_aggregate.id, + CASE WHEN aggregate_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN aggregate_exists THEN to_jsonb(old_aggregate) END, to_jsonb(new_aggregate)); + IF aggregate_exists THEN + UPDATE "${serviceSchema}".world_design_aggregate_epoch + SET draft_revision_epoch = new_aggregate.draft_revision_epoch, updated_at = new_aggregate.updated_at + WHERE id = old_aggregate.id AND draft_revision_epoch = expected_aggregate; + ELSE + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch SELECT (new_aggregate).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate CAS' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_scope FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND scope_type = 'REGION_SUBTREE' AND scope_id = old_region.id::TEXT FOR UPDATE; + scope_exists := FOUND; + IF (scope_exists AND old_scope.draft_scope_revision_epoch <> expected_scope) + OR (NOT scope_exists AND expected_scope <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE epoch' USING ERRCODE = '23514'; + END IF; + IF scope_exists THEN + new_scope := old_scope; + ELSE + new_scope.id := nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'); + new_scope.tenant_id := identity_row.local_tenant_key; + new_scope.version_id := identity_row.local_version_key; + new_scope.scope_type := 'REGION_SUBTREE'; + new_scope.scope_id := old_region.id::TEXT; + END IF; + new_scope.draft_scope_revision_epoch := expected_scope + 1; + new_scope.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_scope_epoch', new_scope.id, + CASE WHEN scope_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN scope_exists THEN to_jsonb(old_scope) END, to_jsonb(new_scope)); + IF scope_exists THEN + UPDATE "${serviceSchema}".world_design_scope_epoch + SET draft_scope_revision_epoch = new_scope.draft_scope_revision_epoch, updated_at = new_scope.updated_at + WHERE id = old_scope.id AND draft_scope_revision_epoch = expected_scope; + ELSE + INSERT INTO "${serviceSchema}".world_design_scope_epoch SELECT (new_scope).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE CAS' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Complete World storage left an unconsumed execution manifest' + USING ERRCODE = '23514'; + END IF; +END; +$$; +-- Explicit internal calls only; deployment roles must deliberately grant access when an +-- authenticated producer exists. Schema owners are the trusted database administration boundary. +REVOKE ALL ON FUNCTION world_store_guarded_region_rows(JSONB, JSONB, JSONB) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql b/services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql new file mode 100644 index 0000000000..361bee13d2 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql @@ -0,0 +1,490 @@ +-- Fresh authored UUID topology is component storage, never permission/release evidence. +-- Retained numeric rows stay unmapped; no canonical identity is inferred from a private key. +ALTER TABLE world_entity_spawn_binding ALTER COLUMN entity_template_id DROP NOT NULL; +ALTER TABLE world_entity_spawn_binding + ADD COLUMN entity_canonical_tenant_id UUID, + ADD COLUMN entity_canonical_version_id UUID, + ADD COLUMN entity_canonical_template_id UUID, + ADD CONSTRAINT ck_world_spawn_reference_representation CHECK ( + (entity_template_id IS NOT NULL AND entity_canonical_tenant_id IS NULL + AND entity_canonical_version_id IS NULL AND entity_canonical_template_id IS NULL) + OR (entity_template_id IS NULL AND entity_canonical_tenant_id IS NOT NULL + AND entity_canonical_version_id IS NOT NULL AND entity_canonical_template_id IS NOT NULL + AND entity_canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_template_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ); +CREATE UNIQUE INDEX uq_world_spawn_canonical_reference ON world_entity_spawn_binding + (tenant_id, version_id, room_id, entity_template_type, + entity_canonical_tenant_id, entity_canonical_version_id, entity_canonical_template_id) + WHERE entity_template_id IS NULL; + +CREATE TABLE world_topology_draft_commit ( + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL CHECK (local_tenant_key > 0), + local_version_key BIGINT NOT NULL CHECK (local_version_key > 0), + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'STORED_PERMISSION_UNVERIFIED'), + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key), + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); +CREATE TABLE world_authored_topology_identity ( + id BIGSERIAL PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + family VARCHAR(50) NOT NULL CHECK (family IN ( + 'REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + private_row_key BIGINT NOT NULL CHECK (private_row_key > 0), + tenant_id BIGINT NOT NULL, + version_id BIGINT NOT NULL, + version_identity_operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_id UUID NOT NULL, + revision_order TEXT NOT NULL, + UNIQUE (target_namespace, canonical_tenant_id, canonical_version_id, family, template_id), + UNIQUE (family, private_row_key), + FOREIGN KEY (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, tenant_id, version_id) + REFERENCES world_topology_draft_commit(request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, version_id) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); + +-- [jooq ignore start] +-- Reuse V29's exact OLD/NEW, source-qualified, transaction-local, consumed manifest. +ALTER TABLE world_region_draft_execution_manifest + DROP CONSTRAINT world_region_draft_execution_manifest_table_name_check, + DROP CONSTRAINT world_region_draft_execution_manifest_check; +ALTER TABLE world_region_draft_execution_manifest + ADD CONSTRAINT ck_world_execution_table CHECK (table_name IN ( + 'region','zone','room','room_exit','generation_rule','world_entity_spawn_binding', + 'world_authored_topology_identity','world_design_aggregate_epoch','world_design_scope_epoch')), + ADD CONSTRAINT ck_world_execution_transition CHECK ( + (row_operation = 'INSERT' AND expected_old IS NULL) + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL + AND table_name IN ('region','world_design_aggregate_epoch','world_design_scope_epoch'))); + +CREATE TRIGGER trg_world_topology_history_immutable BEFORE UPDATE OR DELETE + ON world_topology_draft_commit FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_topology_history_no_truncate BEFORE TRUNCATE + ON world_topology_draft_commit FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_topology_identity() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'INSERT' AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)) THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World UUID mapping requires an exact fresh execution manifest and is immutable' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_world_topology_identity_guard BEFORE INSERT OR UPDATE OR DELETE + ON world_authored_topology_identity FOR EACH ROW EXECUTE FUNCTION world_protect_topology_identity(); +CREATE TRIGGER trg_world_topology_identity_no_truncate BEFORE TRUNCATE + ON world_authored_topology_identity FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_mapped_topology_row() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity + WHERE family = CASE TG_TABLE_NAME WHEN 'world_entity_spawn_binding' + THEN 'WORLD_ENTITY_SPAWN_BINDING' ELSE upper(TG_TABLE_NAME) END + AND private_row_key = OLD.id) THEN + RAISE EXCEPTION 'Mapped UUID World content cannot be changed by numeric writers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_region_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_zone_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_exit_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_generation_rule_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_world_entity_spawn_binding_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +-- The trusted local parsed projection uses canonical protobuf JSON for execution only. +-- Exact original full binding/payload bytes remain the manifest/history authority. As in V29, +-- this typed component seam is not a public caller field or permission evidence; the repository +-- verifies every actual stored payload against the original parsed plan before recording history. +CREATE FUNCTION world_store_guarded_uuid_topology( + p_owner JSONB, p_binding JSONB, p_execution_revisions JSONB +) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + mapping "${serviceSchema}".world_authored_topology_identity%ROWTYPE; + revision JSONB; + mutation JSONB; + payload JSONB; + family TEXT; + table_name TEXT; + content JSONB; + complete_row JSONB; + scope_key BIGINT; + parent_key BIGINT; + other_key BIGINT; + scope_type TEXT; + scope_uuid UUID; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_sorted JSONB; + epoch_row JSONB; + nodes JSONB; + original_revision_identities JSONB; + execution_revision_identities JSONB; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World topology requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World topology storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(p_execution_revisions) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'World typed execution projection must be an array' USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO original_revision_identities + FROM jsonb_array_elements(p_binding->'revisions') WITH ORDINALITY AS original(value,ordinal) + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO execution_revision_identities + FROM jsonb_array_elements(p_execution_revisions) WITH ORDINALITY AS execution(value,ordinal); + IF original_revision_identities IS NULL + OR execution_revision_identities IS DISTINCT FROM original_revision_identities THEN + RAISE EXCEPTION 'World typed execution projection differs from exact original revision identities/order/owner' + USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(value ORDER BY (value->>'revisionOrder')::NUMERIC) INTO nodes + FROM jsonb_array_elements(p_execution_revisions); + IF nodes IS NULL OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' THEN + RAISE EXCEPTION 'Fresh topology requires World input and exact fresh source' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_commit + WHERE request_id = (p_binding->>'requestId')::UUID OR commit_id = (p_binding->>'commitId')::UUID) THEN + RAISE EXCEPTION 'World request/commit already has retained numeric history' USING ERRCODE = '23514'; + END IF; + -- Require a wholly fresh local Version. Retained content is never relabelled or overwritten. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".region + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained region' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".zone + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained zone' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room_exit + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room_exit' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".generation_rule + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained generation_rule' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_entity_spawn_binding + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_entity_spawn_binding' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_aggregate_epoch' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_scope_epoch' USING ERRCODE = '23514'; + END IF; + + FOR revision IN SELECT value FROM jsonb_array_elements(nodes) LOOP + mutation := (revision->>'payload')::JSONB; + family := replace(mutation->>'aggregateType', 'WORLD_DESIGN_AGGREGATE_TYPE_', ''); + scope_type := replace(mutation->>'scopeType', 'WORLD_DESIGN_SCOPE_TYPE_', ''); + IF family NOT IN ('REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING') + OR scope_type NOT IN ('REGION_SUBTREE','ZONE_SUBTREE') + OR mutation->>'operation' IS DISTINCT FROM 'WORLD_DESIGN_MUTATION_OPERATION_UPSERT' + OR mutation->>'commitId' IS DISTINCT FROM p_binding->>'commitId' + OR mutation->>'logicalRevisionId' IS DISTINCT FROM revision->>'revisionId' + OR coalesce(mutation->>'expectedDraftRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'expectedDraftScopeRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'scopeMutationPolicy','WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED') + <> 'WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED' THEN + RAISE EXCEPTION 'Unsupported exact fresh World revision' USING ERRCODE = '23514'; + END IF; + table_name := lower(family); + mapping.id := nextval('"${serviceSchema}".world_authored_topology_identity_id_seq'); + mapping.target_namespace := identity_row.target_namespace; + mapping.canonical_tenant_id := identity_row.canonical_tenant_id; + mapping.canonical_version_id := identity_row.canonical_version_id; + mapping.family := family; + mapping.template_id := (mutation->>'aggregateId')::UUID; + mapping.private_row_key := nextval( + format('%I.%I', '${serviceSchema}', table_name || '_id_seq')::REGCLASS); + mapping.tenant_id := identity_row.local_tenant_key; + mapping.version_id := identity_row.local_version_key; + mapping.version_identity_operation_id := identity_row.operation_id; + mapping.request_id := (p_binding->>'requestId')::UUID; + mapping.commit_id := (p_binding->>'commitId')::UUID; + mapping.revision_id := (revision->>'revisionId')::UUID; + mapping.revision_order := revision->>'revisionOrder'; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_authored_topology_identity', mapping.id, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, to_jsonb(mapping)); + INSERT INTO "${serviceSchema}".world_authored_topology_identity SELECT (mapping).*; + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType','AGGREGATE', + 'scopeId',mapping.template_id::TEXT,'expectedEpoch','0'), + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType',scope_type, + 'scopeId',mutation->>'scopeId','expectedEpoch','0')); + END LOOP; + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO expected_sorted FROM jsonb_array_elements(expected_units); + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + IF expected_sorted IS DISTINCT FROM supplied_units THEN + RAISE EXCEPTION 'World topology requires the exact aggregate and containing tuples' + USING ERRCODE = '23514'; + END IF; + -- Typed mappings are allocated first, then content is inserted in parent-before-child order. + FOR mapping IN SELECT m.* FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = (p_binding->>'requestId')::UUID + ORDER BY CASE m.family WHEN 'REGION' THEN 1 WHEN 'ZONE' THEN 2 WHEN 'ROOM' THEN 3 + WHEN 'ROOM_EXIT' THEN 4 WHEN 'GENERATION_RULE' THEN 5 ELSE 6 END, m.revision_order::NUMERIC + LOOP + SELECT value INTO STRICT revision FROM jsonb_array_elements(nodes) + WHERE value->>'revisionId' = mapping.revision_id::TEXT; + mutation := (revision->>'payload')::JSONB; + family := mapping.family; + table_name := lower(family); + scope_type := replace(mutation->>'scopeType','WORLD_DESIGN_SCOPE_TYPE_',''); + scope_uuid := (mutation->>'scopeId')::UUID; + SELECT m.private_row_key INTO STRICT scope_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.template_id = scope_uuid + AND m.family = CASE scope_type WHEN 'REGION_SUBTREE' THEN 'REGION' ELSE 'ZONE' END; + content := jsonb_build_object('id',mapping.private_row_key,'tenant_id',mapping.tenant_id, + 'version_id',mapping.version_id,'version',0); + CASE family + + WHEN 'REGION' THEN + payload := mutation->'region'; + IF scope_type <> 'REGION_SUBTREE' OR scope_uuid <> mapping.template_id THEN + RAISE EXCEPTION 'Region scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object( + 'name',coalesce(payload->>'name',''),'shard_id',coalesce((payload->>'shardId')::INT,0), + 'weather',coalesce(payload->>'weather',''),'generation_seed',coalesce((payload->>'generationSeed')::BIGINT,0), + 'generator_type',coalesce(payload->>'generatorType',''),'generator_params',coalesce(payload->>'generatorParams',''), + 'spacing_multiplier',coalesce(nullif((payload->>'spacingMultiplier')::FLOAT8,0),1)); + WHEN 'ZONE' THEN + payload := mutation->'zone'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'REGION' + AND m.template_id = (payload->>'regionId')::UUID; + IF (scope_type = 'REGION_SUBTREE' AND scope_key <> parent_key) + OR (scope_type = 'ZONE_SUBTREE' AND scope_uuid <> mapping.template_id) THEN + RAISE EXCEPTION 'Zone scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''),'region_id',parent_key); + WHEN 'ROOM' THEN + payload := mutation->'room'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ZONE' + AND m.template_id = (payload->>'zoneId')::UUID; + SELECT z.region_id INTO STRICT other_key FROM "${serviceSchema}".zone z WHERE z.id = parent_key; + IF scope_key <> (CASE scope_type WHEN 'REGION_SUBTREE' THEN other_key ELSE parent_key END) THEN + RAISE EXCEPTION 'Room scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'description',coalesce(payload->>'description',''),'zone_id',parent_key, + 'name_localized_variants_json',coalesce(payload->>'nameLocalizedVariantsJson',''), + 'description_localized_variants_json',coalesce(payload->>'descriptionLocalizedVariantsJson','')); + WHEN 'ROOM_EXIT' THEN + payload := mutation->'roomExit'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'fromRoomId')::UUID; + SELECT m.private_row_key INTO STRICT other_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'toRoomId')::UUID; + content := content || jsonb_build_object('from_room_id',parent_key,'to_room_id',other_key, + 'direction',coalesce(payload->>'direction',''),'cost',coalesce(nullif((payload->>'cost')::INT,0),1)); + WHEN 'GENERATION_RULE' THEN + payload := mutation->'generationRule'; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'value',coalesce(payload->>'value',''),'scope_type',scope_type,'scope_id',scope_key::TEXT); + WHEN 'WORLD_ENTITY_SPAWN_BINDING' THEN + payload := mutation->'worldEntitySpawnBinding'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'roomId')::UUID; + content := content || jsonb_build_object('room_id',parent_key, + 'entity_template_type',replace(payload->>'entityTemplateType','ENTITY_TEMPLATE_REFERENCE_TYPE_',''), + 'entity_template_id',NULL,'entity_canonical_tenant_id',mapping.canonical_tenant_id, + 'entity_canonical_version_id',mapping.canonical_version_id, + 'entity_canonical_template_id',(payload->>'entityTemplateId')::UUID, + 'spawn_count',coalesce(nullif((payload->>'spawnCount')::INT,0),1), + 'respawn_delay_seconds',coalesce((payload->>'respawnDelaySeconds')::INT,0)); + ELSE RAISE EXCEPTION 'Unsupported World family'; + END CASE; + IF payload IS NULL + OR (content ? 'name' AND btrim(content->>'name') = '') + OR coalesce((content->>'shard_id')::INT,0) < 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) <= 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) IN ('NaN'::FLOAT8,'Infinity'::FLOAT8) + OR coalesce((content->>'cost')::INT,1) < 1 + OR coalesce((content->>'spawn_count')::INT,1) < 1 + OR coalesce((content->>'respawn_delay_seconds')::INT,0) < 0 + OR (family = 'WORLD_ENTITY_SPAWN_BINDING' AND content->>'entity_template_type' NOT IN ('ITEM','NPC')) + OR (family = 'ROOM_EXIT' AND btrim(content->>'direction') = '') THEN + RAISE EXCEPTION 'Invalid fresh World payload' USING ERRCODE = '23514'; + END IF; + IF family IN ('ROOM_EXIT','WORLD_ENTITY_SPAWN_BINDING') THEN + IF NOT EXISTS (SELECT 1 FROM "${serviceSchema}".room r + JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = parent_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key) + OR (family = 'ROOM_EXIT' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".room r JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = other_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key)) THEN + RAISE EXCEPTION 'World endpoint outside exact scope' USING ERRCODE = '23514'; + END IF; + END IF; + -- Populate the full physical row type so the manifest includes every actual column. + EXECUTE format('SELECT to_jsonb(jsonb_populate_record(NULL::%I.%I, $1))', + '${serviceSchema}',table_name) INTO complete_row USING content; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, table_name, mapping.private_row_key, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, complete_row); + EXECUTE format('INSERT INTO %I.%I SELECT (jsonb_populate_record(NULL::%I.%I,$1)).*', + '${serviceSchema}',table_name,'${serviceSchema}',table_name) USING complete_row; + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'), + 'tenant_id',mapping.tenant_id,'version_id',mapping.version_id, + 'aggregate_type',family,'aggregate_id',mapping.private_row_key, + 'draft_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_design_aggregate_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,mapping.tenant_id,mapping.version_id,p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_aggregate_epoch,epoch_row)).*; + END LOOP; + -- Each distinct containing fence advances once, even when multiple affected tuples share it. + FOR revision IN SELECT DISTINCT jsonb_build_object('scope_type',value->>'scopeType','scope_id',value->>'scopeId') + FROM jsonb_array_elements(expected_units) WHERE value->>'scopeType' <> 'AGGREGATE' + LOOP + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'), + 'tenant_id',identity_row.local_tenant_key,'version_id',identity_row.local_version_key, + 'scope_type',revision->>'scope_type','scope_id',revision->>'scope_id', + 'draft_scope_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),(p_binding->>'commitId')::UUID,'world_design_scope_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,identity_row.local_tenant_key,identity_row.local_version_key, + p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_scope_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_scope_epoch,epoch_row)).*; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Unconsumed World topology execution manifest' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_store_guarded_uuid_topology(JSONB,JSONB,JSONB) FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_topology_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_mapped_topology_row() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql b/services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql new file mode 100644 index 0000000000..6b72524bfe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql @@ -0,0 +1,96 @@ +-- Immutable component capture only. The V25 checkpoint is retained, never redefined as graph hash. +CREATE TABLE world_canonical_frozen_topology ( + capture_id UUID PRIMARY KEY CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + publication_fence UUID NOT NULL UNIQUE REFERENCES world_design_publication_fence_attempt(publication_fence), + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + freeze_request_json TEXT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + identity_json TEXT NOT NULL, + intake_json TEXT NOT NULL, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + storage_result_bytes BYTEA NOT NULL CHECK (octet_length(storage_result_bytes) > 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + capture_status VARCHAR(32) NOT NULL CHECK (capture_status = 'CAPTURED_UNVERIFIED'), + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (request_id) REFERENCES world_topology_draft_commit(request_id), + FOREIGN KEY (commit_id) REFERENCES world_topology_draft_commit(commit_id), + FOREIGN KEY (version_identity_operation_id) REFERENCES world_authored_version_identity(operation_id) +); + +-- [jooq ignore start] +CREATE FUNCTION world_check_canonical_frozen_capture() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + commit_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + frozen_evidence JSONB; + identity TEXT; + intake TEXT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical frozen capture requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT commit_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=NEW.request_id AND commit_id=NEW.commit_id + AND version_identity_operation_id=NEW.version_identity_operation_id; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key=commit_row.local_tenant_key AND version_id=commit_row.local_version_key FOR UPDATE; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT to_jsonb(v)::text, to_jsonb(i)::text INTO STRICT identity, intake + FROM "${serviceSchema}".world_authored_version_identity v + JOIN "${serviceSchema}".world_authored_source_intake i ON i.operation_id=v.intake_operation_id + WHERE v.operation_id=NEW.version_identity_operation_id; + frozen_evidence := NEW.freeze_request_json::jsonb; + IF owner_row.owner_freeze_phase <> 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.local_tenant_key IS DISTINCT FROM commit_row.local_tenant_key + OR attempt.version_id IS DISTINCT FROM commit_row.local_version_key + OR attempt.version_identity_operation_id IS DISTINCT FROM NEW.version_identity_operation_id + OR attempt.canonical_tenant_id IS DISTINCT FROM commit_row.canonical_tenant_id + OR attempt.canonical_version_id IS DISTINCT FROM commit_row.canonical_version_id + OR attempt.target_namespace IS DISTINCT FROM commit_row.target_namespace + OR attempt.applied_commit_id IS DISTINCT FROM NEW.commit_id::text + OR frozen_evidence->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR frozen_evidence->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::text + OR frozen_evidence->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::text + OR frozen_evidence->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::text + OR frozen_evidence->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::text + OR frozen_evidence->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR frozen_evidence->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR frozen_evidence->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::text + OR frozen_evidence->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR frozen_evidence->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR frozen_evidence->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR frozen_evidence->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::text + OR NEW.owner_binding_json IS DISTINCT FROM commit_row.owner_binding_json + OR NEW.binding_json IS DISTINCT FROM commit_row.binding_json + OR NEW.binding_digest IS DISTINCT FROM commit_row.binding_digest + OR NEW.graph_bytes IS DISTINCT FROM commit_row.graph_bytes + OR NEW.graph_sha256 IS DISTINCT FROM commit_row.graph_sha256 + OR NEW.storage_result_bytes IS DISTINCT FROM commit_row.result_bytes + OR NEW.identity_json IS DISTINCT FROM identity OR NEW.intake_json IS DISTINCT FROM intake THEN + RAISE EXCEPTION 'Canonical frozen capture differs from exact original storage and FROZEN checkpoint' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_frozen_insert BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_check_canonical_frozen_capture(); +CREATE TRIGGER trg_world_canonical_frozen_immutable BEFORE UPDATE OR DELETE + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_frozen_no_truncate BEFORE TRUNCATE + ON world_canonical_frozen_topology FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql b/services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql new file mode 100644 index 0000000000..cdc152ce4c --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql @@ -0,0 +1,30 @@ +-- Root 4b059ade (2026-10-14 20:18) approved this forward repair in the guarded graph owner stage. +-- Restore installed V27.2 disjoint legacy UPDATE behavior after the V1004 component guard. +-- Canonical mutations and DELETE retain the exact guarded branch before this fastpath. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1004 legacy reservation claim anchor'; + END IF; + original := replace(original, anchor, $replacement$ IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + IF TG_OP = 'UPDATE' AND OLD.tenant_id = NEW.tenant_id + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation retained + WHERE retained.tenant_key = NEW.tenant_id AND retained.claim_kind = 'LEGACY_NUMERIC') THEN + RETURN NEW; + END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation$replacement$); + EXECUTE original; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql b/services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql new file mode 100644 index 0000000000..e920f23870 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql @@ -0,0 +1,39 @@ +-- Preserve exact immutable schema-2 history; only new captures use schema 3. +ALTER TABLE world_authored_graph_snapshot + DROP CONSTRAINT ck_world_authored_graph_snapshot_scope; +ALTER TABLE world_authored_graph_snapshot + ADD CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version IN (2, 3) + ); + +-- [jooq ignore start] +CREATE FUNCTION world_require_new_digest_schema3_capture() RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_TABLE_NAME = 'world_authored_graph_snapshot' THEN + IF NEW.digest_schema_version IS DISTINCT FROM 3 THEN + RAISE EXCEPTION 'New World graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + ELSE + IF (NEW.freeze_request_json::jsonb)->>'digestSchemaVersion' IS DISTINCT FROM '3' THEN + RAISE EXCEPTION 'New canonical graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_authored_graph_snapshot_schema3 BEFORE INSERT + ON world_authored_graph_snapshot FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +CREATE TRIGGER trg_world_canonical_frozen_00_schema3 BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java new file mode 100644 index 0000000000..18f82c9a88 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java @@ -0,0 +1,1034 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import 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.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; +import net.firedevops.firemud.worldmanagement.repository.RegionRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Bounded native upgrade from the literal d7c8f84 World/Saga parent. External source and Version + * values are controlled; real World repositories retain them with all storage guards enabled. The + * parent World row is legacy storage, not a Human frozen graph or canonical activation claim. + * Physical Docker execution with zero skips is required to qualify this definition. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldGuardedAuthoredGraphCapturePostgresIntegrationTest { + private static final String HISTORY = "flyway_schema_history_world_management_service"; + private static final String NAMESPACE = "firemud"; + + // Exact SHA-256 bytes at d7c8f84fa947644a651304205803c3919c81684e: 31 World and 3 Saga. + private static final Map PARENT_MIGRATIONS = + Map.ofEntries( + Map.entry( + "V1000__create_saga_schema.sql", + "13f58ab66bd9c12483e113c8758ef9907ab3d14d47f61a298dd18f929d5aa537"), + Map.entry( + "V1001__saga_instance_table.sql", + "ebc4bbfd1a10314850e19ca6017d654a98c2ee4f5b95d1cce2ee078d990eb2bf"), + Map.entry( + "V1002__saga_step_table.sql", + "d9d98a2e51d53d78d17d27b15fe696e8b1e161af7c6de142680ec7b8a0dc7c31"), + Map.entry( + "V10__room_exit_direction.sql", + "9b174b153af563916b409abdad3da24f2d88f8a547de6d2b1f1085da3f06264e"), + Map.entry( + "V11__room_localized_text_variants.sql", + "cded77589b64b740689276c96e346ffff97226294b72ef184ab9ae5eaeea7b65"), + Map.entry( + "V12__world_instance_activation.sql", + "3fb5eecc00edb542dd45dd8dd11a632732f47277f96cae4bfc26ebf0f905fa62"), + Map.entry( + "V13__world_instance_termination.sql", + "894f7002fe67c6c65ab04018be7802c78b505666a0d16e2d2794eac4fccd54d4"), + Map.entry( + "V14__room_instance_topology.sql", + "4134d648bb29fd22e4e9d0b0df38454a698f1ab9449c1118c027a4e256658bc4"), + Map.entry( + "V15__zone_instance_topology.sql", + "413445894f5f39eb726e5824566c7bacab8ab81e7c51aadfe3d5917544395677"), + Map.entry( + "V16__runtime_world_event_scope.sql", + "905ac02e6a65308ab70fc5e986608131043c7eec7a2ebd1615f13652d36a4ffb"), + Map.entry( + "V17__world_instance_remap_set.sql", + "286a77a1110a9f3b8d7f88a6a829edb5551dbef73f02de1cdbf184c5947181d8"), + Map.entry( + "V18__version_scoped_world_templates.sql", + "02b07237b04c64d9f4215c42b4cefe31bdc05bd066c6f0823f14733a9772819b"), + Map.entry( + "V19__world_design_mutation_ledger.sql", + "fbbec4b460ce5aa9d4ea9dce70b156840c4cb8d99a0a1589771bad7a220d2f59"), + Map.entry( + "V1__init.sql", "7c65f75f6d2e32f7c07e24ea0260768e5660987a54a9148cef3422f5352bee64"), + Map.entry( + "V20__world_entity_spawn_binding.sql", + "ac5c8c2c326f47c4782c5595d7bbde478320ebb05bcde14f8e02a3bee158afd7"), + Map.entry( + "V21__scoped_generation_rules.sql", + "9e358fe5dd4a41f92a5b16681ad2adc7d24b969e5f476152228b2462974e68dd"), + Map.entry( + "V22__room_instance_internal_record_naming.sql", + "f56fce69e28c9dd9457dc508b016657480abd78d2a3190e782b8e2c0e3c4f340"), + Map.entry( + "V23.0.1__world_run_owned_fixture_launch_binding.sql", + "f014485e67b32b6404bb5cd40dc5568c2d1d9bc1993bafe826660c5b438ceecc"), + Map.entry( + "V23.1__world_authored_source_intake.sql", + "a7ac30d48da1911eb3395716e827ac0f0ec612970d4f40b5a27530d634430445"), + Map.entry( + "V23__initial_admission_bind_hold.sql", + "5e6f6070a02fbf09836dcc663ee3c12390dcb0dbea33a9e15ddd021a913ca1f1"), + Map.entry( + "V24__world_canonical_tenant_mutation_guard.sql", + "6ad0933008cea2d0fe28c8e247277950f789ac1f6cc061f1204b23cb044e82ea"), + Map.entry( + "V25__world_design_publication_fence.sql", + "c852a2e24232df5aec8628c1046570b49edb465a416bbdf942b60fe80ae17f94"), + Map.entry( + "V26__world_complete_launch_binding.sql", + "171595e883d8d459bfd05b8331cc2ace6faf41406b26a743cdc6d133cba33f7e"), + Map.entry( + "V27.1__world_publication_owner_binding.sql", + "93def8666763a08b1db34fd3db88cfa9eea0d5bc7bf836cffe9ff8766d0468f1"), + Map.entry( + "V27.2__world_legacy_tenant_claim_concurrency.sql", + "5a0c8de956baf2dce47e45bff6b3e022dd24d6a4c7c0ebeb4d55fdafb757f9bc"), + Map.entry( + "V27__world_authored_version_identity.sql", + "e9ff823152776361f2ac79d08b6dddce72105892fce0706041e8956994d8db0d"), + Map.entry( + "V2__add_tenant_and_expiration.sql", + "180a5c49ce5dc144daeb442c833921a410c51828f8196d1bbb4e6fe2d1955838"), + Map.entry( + "V3__world_events.sql", + "b6aaa18a6f01c7270e062a9cf8d2b13e0a57a092e7f418b87eaa382e3c9f3f3d"), + Map.entry( + "V4__room_exits.sql", + "02fbaee1e529649fa6dbe803795ac78cc40f5121735399131592b32bd23cb23a"), + Map.entry( + "V5__generation_rules.sql", + "27ba4f1827c6eafa14ccd6a4b85c9eb5c3de312ee85cdcae2da846ee1d8817a4"), + Map.entry( + "V6__region_shard.sql", + "a8bca5bad73f02936a8971cc9c34c19921d02bee55f860cad08d2c73932025cb"), + Map.entry( + "V7__optimistic_locking_and_indexes.sql", + "40d428bf21b99351068ee6cf11778ab3171f720f00ad2d8c9230b245093f9261"), + Map.entry( + "V8__region_generation_metadata.sql", + "a3bc7811eff6743f771346188f811b14d882356f67ccdbf6213bb2cc87695570"), + Map.entry( + "V9__region_spacing_multiplier.sql", + "5a5e2279d78b88cfad19802bbdf37416df714ee864265b08472b61fb234b6c32")); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesInDefaultOrder( + @TempDir Path parentMigrations) throws Exception { + Path root = repositoryRoot(); + Path worldMigrations = + root.resolve("services/world-management-service/src/main/resources/db/migration"); + Path sagaMigrations = root.resolve("services/common-saga/src/main/resources/db/migration/saga"); + for (var entry : PARENT_MIGRATIONS.entrySet()) { + Path original = worldMigrations.resolve(entry.getKey()); + if (!Files.exists(original)) original = sagaMigrations.resolve(entry.getKey()); + byte[] originalBytes = Files.readAllBytes(original); + assertThat( + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(originalBytes))) + .as("literal parent artifact %s", entry.getKey()) + .isEqualTo(entry.getValue()); + Files.copy(original, parentMigrations.resolve(entry.getKey())); + } + + String schema = "world_parent_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + try { + Flyway parent = flyway(dataSource, schema, "filesystem:" + parentMigrations); + assertThat(parent.getConfiguration().isOutOfOrder()).isFalse(); + parent.migrate(); + parent.validate(); + assertThat(history(dsl)).hasSize(34); + assertThat( + dsl.fetchSingle( + "SELECT max(version::int) FROM " + HISTORY + " WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1002); + assertThat( + dsl.fetch("SELECT script FROM " + HISTORY + " WHERE version IS NOT NULL") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(PARENT_MIGRATIONS.keySet()); + assertThat( + dsl.fetchSingle("SELECT to_regclass(?)", schema + ".world_authored_graph_snapshot") + .get(0)) + .isNull(); + + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var sourceOwner = new WorldAuthoredSourceIntakeRepository(dsl); + var versionOwner = new WorldAuthoredVersionIdentityRepository(dsl); + // This ordinary legacy row predates any graph/association migration and is independently + // scoped. + long worldId = + dsl.fetchSingle( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, runtime_flags_json, " + + "generation_config_revision, release_bundle_id, published_release_bundle_ref, " + + "version_state_epoch, status) VALUES (7001, 8101, 17, 'retained-parent-world', " + + "'retained-parent-descriptor', 11, '{}', 'parent-generation', 77, " + + "'retained-parent-release', 3, 'PREPARING') RETURNING id") + .get(0, Long.class); + dsl.execute( + "INSERT INTO region_instance (tenant_id, game_instance_id, world_instance_id, " + + "name, generation_seed) VALUES (7001, 8101, ?, 'Retained parent region', 42)", + worldId); + long sagaId = + dsl.fetchSingle( + "INSERT INTO saga_instance (saga_name, state) " + + "VALUES ('retained-parent-saga', 'PENDING') RETURNING id") + .get(0, Long.class); + dsl.execute( + "INSERT INTO saga_step (instance_id, name, status, attempt) " + + "VALUES (?, 'retained-parent-step', 'PENDING', 2)", + sagaId); + + AuthoredWorldSourceEvidence upstream = controlledSource(); + UUID intakeRequest = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt source = + Objects.requireNonNull( + write.execute(status -> sourceOwner.acceptFresh(NAMESPACE, intakeRequest, upstream))); + UUID canonicalVersion = UUID.randomUUID(); + var versionEvidence = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + upstream.canonicalTenantId(), + upstream.worldSlug(), + upstream.operationId(), + upstream.evidenceDigest(), + 9000000042L), + upstream, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 3L); + WorldAuthoredVersionIdentityReceipt version = + Objects.requireNonNull( + write.execute(status -> versionOwner.acceptFresh(source, versionEvidence))); + assertThat(source.localTenantKey()).isNotEqualTo(7001L); + assertThat(version.localVersionKey()).isNotEqualTo(version.gameDesignVersionId()); + assertThat(sourceOwner.read(NAMESPACE, intakeRequest)).contains(source); + assertThat( + versionOwner.readByCanonicalVersion( + NAMESPACE, upstream.canonicalTenantId(), upstream.worldSlug(), canonicalVersion)) + .contains(version); + + List originalHistory = history(dsl); + Map> originalColumns = new LinkedHashMap<>(); + Map> originalRows = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_authored_version_identity", + "world_instance", + "region_instance", + "saga_instance", + "saga_step")) { + List columns = + dsl.fetch( + "SELECT column_name FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position", + schema, + table) + .getValues(0, String.class); + assertThat(columns).isNotEmpty(); + originalColumns.put(table, columns); + originalRows.put(table, retainedRows(dsl, table, columns)); + assertThat(originalRows.get(table)).isNotEmpty(); + } + + // Actual service filesystem locations, including Saga; no repair, baseline, or outOfOrder. + Flyway current = + flyway( + dataSource, schema, "filesystem:" + worldMigrations, "filesystem:" + sagaMigrations); + assertThat(current.getConfiguration().isOutOfOrder()).isFalse(); + current.migrate(); + current.validate(); + assertThat(history(dsl).subList(0, 34)).isEqualTo(originalHistory); + assertThat(history(dsl)).hasSize(40); + assertThat( + dsl.fetch( + "SELECT version FROM " + + HISTORY + + " WHERE installed_rank > 34 ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactlyElementsOf(List.of("1003", "1004", "1005", "1006", "1007", "1007.1")); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM " + HISTORY + " WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(40L); + for (var entry : originalColumns.entrySet()) { + assertThat(retainedRows(dsl, entry.getKey(), entry.getValue())) + .as("exact original column bytes for %s", entry.getKey()) + .isEqualTo(originalRows.get(entry.getKey())); + } + assertThat(sourceOwner.read(NAMESPACE, intakeRequest)).contains(source); + assertThat( + versionOwner.readByCanonicalVersion( + NAMESPACE, upstream.canonicalTenantId(), upstream.worldSlug(), canonicalVersion)) + .contains(version); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_authored_graph_snapshot") + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT to_regclass(?)", schema + ".world_canonical_instance_association") + .get(0)) + .isNull(); + assertThat( + dsl.fetchSingle( + "SELECT to_regclass(?)", schema + ".world_canonical_instance_preparation") + .get(0)) + .isNull(); + 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 = 'D'", + schema) + .get(0, Long.class)) + .isZero(); + // Two distinct legacy rows must update without serializing on their shared reservation. + long otherRegion = + dsl.fetchSingle( + "INSERT INTO region_instance (tenant_id, game_instance_id, world_instance_id, name, generation_seed) " + + "VALUES (7001, 8101, ?, 'Independent retained region', 43) RETURNING id", + worldId) + .get(0, Long.class); + long firstRegion = + dsl.fetchSingle( + "SELECT min(id) FROM region_instance WHERE world_instance_id = ?", worldId) + .get(0, Long.class); + try (var first = dataSource.getConnection(); + var second = dataSource.getConnection()) { + first.setAutoCommit(false); + second.setAutoCommit(false); + try (var statement = first.createStatement()) { + statement.executeUpdate( + "UPDATE region_instance SET name = 'held legacy row' WHERE id = " + firstRegion); + } + try (var statement = second.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '1000ms'"); + assertThat( + statement.executeUpdate( + "UPDATE region_instance SET name = 'independent legacy row' WHERE id = " + + otherRegion)) + .isEqualTo(1); + } finally { + second.rollback(); + first.rollback(); + } + } + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + source.operationId())) + .hasMessageContaining("immutable"); + assertThat( + retainedRows( + dsl, + "world_authored_source_intake", + originalColumns.get("world_authored_source_intake"))) + .isEqualTo(originalRows.get("world_authored_source_intake")); + } finally { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + @Test + void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThreeGuard() + throws Exception { + String schema = "world_retained_schema2_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(manager); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + Path root = repositoryRoot(); + String worldLocation = + "filesystem:" + + root.resolve("services/world-management-service/src/main/resources/db/migration"); + String sagaLocation = + "filesystem:" + root.resolve("services/common-saga/src/main/resources/db/migration/saga"); + try { + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(HISTORY) + .placeholders(Map.of("serviceSchema", schema)) + .locations(worldLocation, sagaLocation) + .target(MigrationVersion.fromVersion("1006")) + .load() + .migrate(); + + AuthoredWorldSourceEvidence upstream = controlledSource(); + UUID intakeRequest = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt intake = + Objects.requireNonNull( + write.execute( + status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, intakeRequest, upstream))); + UUID canonicalVersion = UUID.randomUUID(); + long gameDesignVersion = 43L; + var versionState = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + upstream.canonicalTenantId(), + upstream.worldSlug(), + upstream.operationId(), + upstream.evidenceDigest(), + gameDesignVersion), + upstream, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + WorldAuthoredVersionIdentityReceipt version = + Objects.requireNonNull( + write.execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(intake, versionState))); + + String publicationRequest = "retained-schema2-repository"; + String requestDigest = "b".repeat(64); + String contentDigest = "c".repeat(64); + String captureRequestDigest = "d".repeat(64); + String legacyCheckpoint = "version:" + version.localVersionKey(); + String workflow = + PublicationDigestRequestBinding.full( + upstream.canonicalTenantId().toString(), + Long.toString(gameDesignVersion), + publicationRequest) + .derivedWorkflowIdentity(); + var publication = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + upstream.canonicalTenantId(), + canonicalVersion, + version.operationId(), + gameDesignVersion, + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + publicationRequest, + requestDigest, + 1L, + workflow); + var fenceRepository = + new WorldDesignPublicationFenceRepository( + dsl, new WorldAuthoredSourceIntakeRepository(dsl)); + // These are controlled predecessor-checkpoint fields for repository retention only. The + // truthful legacy version token is not a complete commit ID, and no producer or APPLIED + // authority is inferred from it. + var frozen = + Objects.requireNonNull( + write.execute( + status -> + fenceRepository.claimFreeze( + publication, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + legacyCheckpoint, contentDigest, 2)))); + var request = + new WorldAuthoredGraphSnapshot.CaptureRequest( + NAMESPACE, + upstream.canonicalTenantId(), + canonicalVersion, + intake.intakeRequestId(), + frozen.publicationFence(), + publicationRequest, + requestDigest, + 1L, + workflow, + legacyCheckpoint, + contentDigest, + 2, + List.of()); + byte[] graphBytes = + new WorldAuthoredGraphReader(dsl) + .readAndValidateGraph(intake.localTenantKey(), version.localVersionKey()) + .encode(new tools.jackson.databind.ObjectMapper()); + assertThat(new String(graphBytes, StandardCharsets.UTF_8)) + .isEqualTo( + "{\"snapshotSchemaVersion\":1,\"regions\":[],\"zones\":[],\"rooms\":[]," + + "\"roomExits\":[],\"generationRules\":[]," + + "\"worldEntitySpawnBindings\":[]}"); + var snapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); + WorldAuthoredGraphSnapshot stored = + Objects.requireNonNull( + write.execute( + status -> { + var provenance = snapshotRepository.lockAndResolve(request); + return snapshotRepository.insertAndReadback( + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + provenance.targetNamespace(), + provenance.canonicalTenantId(), + provenance.canonicalVersionId(), + provenance.versionIdentityOperationId(), + provenance.worldSlug(), + provenance.gameDesignVersionId(), + provenance.localVersionKey(), + provenance.localTenantKey(), + (short) 1, + provenance.intakeOperationId(), + provenance.intakeRequestId(), + provenance.intakeRequestDigest(), + provenance.sourceOperationId(), + provenance.sourceEvidenceDigest(), + provenance.intakeReceiptDigest(), + frozen.publicationFence(), + publicationRequest, + requestDigest, + 1L, + workflow, + legacyCheckpoint, + contentDigest, + 2, + captureRequestDigest, + "[]", + "[]", + graphBytes, + WorldAuthoredGraphSnapshotCapture.sha256(graphBytes), + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)); + })); + List columns = + dsl.fetch( + "SELECT column_name FROM information_schema.columns " + + "WHERE table_schema=? AND table_name='world_authored_graph_snapshot' " + + "ORDER BY ordinal_position", + schema) + .getValues(0, String.class); + List before = retainedRows(dsl, "world_authored_graph_snapshot", columns); + assertThat(before).hasSize(1); + + flyway(source, schema, worldLocation, sagaLocation).migrate(); + + assertThat( + dsl.fetch( + "SELECT version FROM " + + HISTORY + + " WHERE version IN ('1007','1007.1') ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactly("1007", "1007.1"); + assertThat(retainedRows(dsl, "world_authored_graph_snapshot", columns)).isEqualTo(before); + WorldAuthoredGraphSnapshot retained = + snapshotRepository.findByFence(frozen.publicationFence()); + assertThat(retained).isNotNull(); + assertThat(retained.snapshotId()).isEqualTo(stored.snapshotId()); + assertThat(retained.digestSchemaVersion()).isEqualTo(2); + assertThat(retained.appliedCommitId()).isEqualTo(legacyCheckpoint); + assertThat(retained.graphBytes()).containsExactly(graphBytes); + assertThat(retained.graphSha256()).isEqualTo(stored.graphSha256()); + assertThat(retained.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + } finally { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + @Test + void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() throws Exception { + String schema = "world_guarded_graph_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(manager); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + Path root = repositoryRoot(); + try { + flyway( + source, + schema, + "filesystem:" + + root.resolve( + "services/world-management-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")) + .migrate(); + var upstream = controlledSource(); + var intake = + Objects.requireNonNull( + write.execute( + status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); + var state = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + upstream.canonicalTenantId(), + upstream.worldSlug(), + upstream.operationId(), + upstream.evidenceDigest(), + 42L), + upstream, + UUID.randomUUID(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + var version = + Objects.requireNonNull( + write.execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); + var fence = + new WorldDesignPublicationFenceRepository( + dsl, new WorldAuthoredSourceIntakeRepository(dsl)); + var mapper = new tools.jackson.databind.ObjectMapper(); + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + var plan = topologyPlan(intake, version); + var stored = Objects.requireNonNull(write.execute(status -> topology.store(plan))); + assertThat(stored.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(topology.readCommitted(plan)).isPresent(); + var replay = Objects.requireNonNull(write.execute(status -> topology.store(plan))); + assertThat(replay.graphBytes()).isEqualTo(stored.graphBytes()); + assertThat(replay.resultBytes()).isEqualTo(stored.resultBytes()); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_authored_topology_identity") + .get(0, Long.class)) + .isEqualTo(7L); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_region_draft_execution_manifest") + .get(0, Long.class)) + .isZero(); + List rowsBefore = + dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") + .getValues(0, String.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE region SET name = 'naked' WHERE tenant_id = ?", + intake.localTenantKey())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(topology.readCommitted(plan).orElseThrow().resultBytes()) + .isEqualTo(stored.resultBytes()); + + var digest = + new WorldDraftDesignDigestServiceImpl( + new RegionRepository(dsl), + new ZoneRepository(dsl), + new RoomRepository(dsl), + new RoomExitRepository(dsl), + new GenerationRuleRepository(dsl), + new WorldEntitySpawnBindingRepository(dsl), + mapper); + var actual = + digest.getDraftDesignDigest( + Long.toString(intake.localTenantKey()), Long.toString(version.localVersionKey())); + assertThat(actual.digestSchemaVersion()).isEqualTo(3); + assertThat(actual.appliedCommitId()).isEqualTo("version:" + version.localVersionKey()); + String publicationRequest = "guarded-capture"; + String workflow = + PublicationDigestRequestBinding.full( + upstream.canonicalTenantId().toString(), "42", publicationRequest) + .derivedWorkflowIdentity(); + var owner = plan.ownerBinding(); + var publication = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + "f".repeat(64), + 1L, + workflow); + // The checkpoint comes from the actual current digest writer. It does not prove APPLIED. + var frozen = + Objects.requireNonNull( + write.execute( + status -> + fence.claimFreeze( + publication, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + actual.appliedCommitId(), + actual.contentDigest(), + actual.digestSchemaVersion())))); + var tuples = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + var capture = + new WorldAuthoredGraphSnapshot.CaptureRequest( + NAMESPACE, + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + frozen.publicationFence(), + publicationRequest, + publication.requestDigest(), + publication.versionStateEpoch(), + workflow, + actual.appliedCommitId(), + actual.contentDigest(), + actual.digestSchemaVersion(), + tuples); + // Current capture must deny the actual synthetic checkpoint rather than invent APPLIED rows. + var snapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); + var graphCapture = + new WorldAuthoredGraphSnapshotCapture(dsl, digest, snapshotRepository, mapper); + assertThatThrownBy(() -> write.execute(status -> graphCapture.capture(capture))) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException.class) + .hasMessageContaining("retained V19 revision history"); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_authored_graph_snapshot") + .get(0, Long.class)) + .isZero(); + // Positive canonical frozen capture is intentionally unavailable until the actual commit + // token exists. + assertThatThrownBy(() -> new WorldCanonicalFrozenTopology.Request(plan, capture)) + .hasMessageContaining("exact selected complete commit"); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_canonical_frozen_topology") + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") + .getValues(0, String.class)) + .isEqualTo(rowsBefore); + } finally { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static WorldDraftTopologyCommitPlan topologyPlan( + WorldAuthoredSourceIntakeReceipt intake, WorldAuthoredVersionIdentityReceipt version) + throws Exception { + UUID commit = UUID.randomUUID(); + UUID region = UUID.randomUUID(); + UUID zone = UUID.randomUUID(); + UUID room = UUID.randomUUID(); + UUID otherRoom = UUID.randomUUID(); + List mutations = + List.of( + mutation( + commit, + region, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + region) + .setRegion(RegionDesignMutation.newBuilder().setName("Guarded region")) + .build(), + mutation( + commit, zone, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, region) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Guarded zone") + .setRegionId(region.toString())) + .build(), + mutation( + commit, room, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, region) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Guarded room") + .setZoneId(zone.toString())) + .build(), + mutation( + commit, + otherRoom, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + region) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Other room") + .setZoneId(zone.toString())) + .build(), + mutation( + commit, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + region) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(room.toString()) + .setToRoomId(otherRoom.toString()) + .setDirection("EAST")) + .build(), + mutation( + commit, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + region) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("fixed")) + .build(), + mutation( + commit, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + region) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(room.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(UUID.randomUUID().toString())) + .build()); + var revisions = new ArrayList(); + var units = new ArrayList(); + for (var mutation : mutations) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + String family = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + region.toString(), + "0")); + } + var upstream = intake.source(); + var binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + upstream.canonicalTenantId(), + version.canonicalVersionId(), + version.gameDesignVersionId(), + upstream.sourceGameTenantKey(), + upstream.sourceGameRowId(), + upstream.sourceGameTenantKey(), + upstream.provenanceKind()), + UUID.randomUUID(), + commit, + "controlled-component-base", + revisions, + units); + var owner = + new OwnerBinding( + NAMESPACE, + upstream.canonicalTenantId(), + version.canonicalVersionId(), + version.operationId(), + version.gameDesignVersionId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + upstream.operationId(), + upstream.evidenceDigest(), + intake.receiptDigest()); + return WorldDraftTopologyCommitPlan.create(binding, owner); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, WorldDesignAggregateType family, UUID region) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(family) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(region.toString()); + } + + private static AuthoredWorldSourceEvidence controlledSource() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String request = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registration, + tenant, + "upgrade-tenant", + "upgrade-world", + "Retained owner world"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + operation, + request, + tenant, + "upgrade-tenant", + "upgrade-world", + "Retained owner world", + 77L, + "parent-source-owner", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + operation, + request, + tenant, + "upgrade-tenant", + "upgrade-world", + "Retained owner world", + 77L, + "parent-source-owner", + "NEW_GAME_ROW")); + } + + private static Flyway flyway(DriverManagerDataSource source, String schema, String... locations) { + return Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(HISTORY) + .placeholders(Map.of("serviceSchema", schema)) + .locations(locations) + .load(); + } + + private static List history(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(t)::text FROM " + + HISTORY + + " t WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static List retainedRows( + DSLContext dsl, String table, List originalColumns) { + // New columns are checked separately; compare every original column without synthesizing + // values. + String projection = + originalColumns.stream() + .map(column -> "\"" + column + "\"") + .collect(java.util.stream.Collectors.joining(", ")); + return dsl.fetch( + "SELECT to_jsonb(retained)::text FROM (SELECT xmin::text AS retained_xmin, " + + projection + + " FROM " + + table + + ") retained ORDER BY to_jsonb(retained)::text") + .getValues(0, String.class); + } + + private static Path repositoryRoot() { + Path candidate = Path.of("").toAbsolutePath(); + while (candidate != null) { + if (Files.exists(candidate.resolve("settings.gradle.kts"))) return candidate; + candidate = candidate.getParent(); + } + throw new IllegalStateException("Unable to locate repository filesystem migrations"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java index 0ddd055ab5..c3539252bf 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java @@ -114,8 +114,41 @@ void computesDigestFromVersionScopedTemplateRows() { assertEquals("1", digest.tenantId()); assertEquals("7", digest.scopeValue()); assertEquals("version:7", digest.appliedCommitId()); - assertEquals(2, digest.digestSchemaVersion()); + assertEquals(3, digest.digestSchemaVersion()); Mockito.verify(regionRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L); Mockito.verify(regionRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); } + + @Test + void canonicalSpawnReferenceAffectsSchemaThreeDigestAndMixedReferencesDeny() { + var regions = Mockito.mock(RegionRepository.class); + var zones = Mockito.mock(ZoneRepository.class); + var rooms = Mockito.mock(RoomRepository.class); + var exits = Mockito.mock(RoomExitRepository.class); + var rules = Mockito.mock(GenerationRuleRepository.class); + var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); + var service = + new WorldDraftDesignDigestServiceImpl( + regions, zones, rooms, exits, rules, spawns, new ObjectMapper()); + var room = new net.firedevops.firemud.worldmanagement.entity.Room(); + room.setId(11L); + var spawn = new net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding(); + spawn.setId(12L); + spawn.setRoom(room); + spawn.setEntityTemplateType("NPC"); + spawn.setEntityCanonicalTenantId(java.util.UUID.randomUUID()); + spawn.setEntityCanonicalVersionId(java.util.UUID.randomUUID()); + spawn.setEntityCanonicalTemplateId(java.util.UUID.randomUUID()); + Mockito.when(spawns.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of(spawn)); + var before = service.getDraftDesignDigest("1", "7"); + assertEquals(3, before.digestSchemaVersion()); + spawn.setEntityCanonicalTemplateId(java.util.UUID.randomUUID()); + org.junit.jupiter.api.Assertions.assertNotEquals( + before.contentDigest(), service.getDraftDesignDigest("1", "7").contentDigest()); + spawn.setEntityTemplateId(9L); + assertThrows(IllegalStateException.class, () -> service.getDraftDesignDigest("1", "7")); + spawn.setEntityTemplateId(null); + spawn.setEntityCanonicalVersionId(null); + assertThrows(IllegalStateException.class, () -> service.getDraftDesignDigest("1", "7")); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java new file mode 100644 index 0000000000..17b5bc8aa8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +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.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; + +/** Typed component input only; these values supply no authenticated owner authority. */ +class WorldGuardedAuthoredTopologyPlanTest { + private final UUID tenant = UUID.randomUUID(); + private final UUID version = UUID.randomUUID(); + private final UUID commit = UUID.randomUUID(); + private final UUID region = UUID.randomUUID(); + private final OwnerBinding owner = + new OwnerBinding( + "firemud", + tenant, + version, + UUID.randomUUID(), + 42L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + + @Test + void retainsOriginalEnclosingBytesAndDerivesExactScope() throws Exception { + var binding = binding(json(mutation()), true); + var plan = WorldDraftTopologyCommitPlan.create(binding, owner); + assertThat(plan.binding().canonicalBytes()).isEqualTo(binding.canonicalBytes()); + assertThat(plan.graph().nodes()).hasSize(1); + assertThat(plan.graph().nodes().getFirst().scopeId()).isEqualTo(region); + assertThat(WorldDraftTopologyInputGraph.STATUS).isEqualTo("PURE_UNVERIFIED"); + } + + @Test + void refusesMissingAffectedScope() throws Exception { + var binding = binding(json(mutation()), false); + assertThatThrownBy(() -> WorldDraftTopologyCommitPlan.create(binding, owner)) + .hasMessageContaining("affected units"); + } + + @Test + void refusesUnknownPayloadFieldsAndDuplicateJsonKeys() throws Exception { + String payload = json(mutation()); + var unknown = + binding(payload.substring(0, payload.length() - 1) + ",\"unexpected\":true}", true); + assertThatThrownBy(() -> WorldDraftTopologyCommitPlan.create(unknown, owner)) + .isInstanceOf(IllegalArgumentException.class); + var duplicate = + binding( + payload.substring(0, payload.length() - 1) + ",\"commitId\":\"" + commit + "\"}", true); + assertThatThrownBy(() -> WorldDraftTopologyCommitPlan.create(duplicate, owner)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesPayloadCommitSubstitutionAndChangedScope() throws Exception { + var changedCommit = + binding( + json(mutation().toBuilder().setCommitId(UUID.randomUUID().toString()).build()), true); + assertThatThrownBy(() -> WorldDraftTopologyCommitPlan.create(changedCommit, owner)) + .hasMessageContaining("commit/revision identity"); + var changedScope = + binding( + json(mutation().toBuilder().setScopeId(UUID.randomUUID().toString()).build()), true); + assertThatThrownBy(() -> WorldDraftTopologyCommitPlan.create(changedScope, owner)) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldDesignMutationRevision mutation() { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(region.toString()) + .setAggregateId(region.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(region.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("Strict region")) + .build(); + } + + private DraftCommitBinding binding(String payload, boolean completeScope) { + var aggregate = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + region.toString(), + "AGGREGATE", + region.toString(), + "0"); + var scope = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + region.toString(), + "REGION_SUBTREE", + region.toString(), + "0"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 42L, "source-key", 77L, "source-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + commit, + "component-base", + List.of(new RevisionPayload("0", region, Owner.WORLD_MANAGEMENT, payload)), + completeScope ? List.of(aggregate, scope) : List.of(aggregate)); + } + + private static String json(WorldDesignMutationRevision mutation) throws Exception { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } +} From 3ae5fffd4aec52101739c78d89cd6bd0ce5f9935 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:12:16 +1300 Subject: [PATCH 2/7] Fix canonical spawn snapshot codec and stable owner binding bytes --- .../runtime-and-data.md | 4 +- .../world-runtime-and-movement.md | 10 +- .../tenant/WorldAuthoredGraph.java | 86 +++++++++-- .../tenant/WorldAuthoredGraphReader.java | 47 +++++- ...orldCanonicalFrozenTopologyRepository.java | 5 +- .../WorldDraftTopologyCommitRepository.java | 15 +- ...edGraphCapturePostgresIntegrationTest.java | 116 ++++++++++++++- .../tenant/WorldAuthoredGraphCodecTest.java | 140 ++++++++++++++++++ .../WorldOwnerBindingSerializationTest.java | 50 +++++++ 9 files changed, 442 insertions(+), 31 deletions(-) create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOwnerBindingSerializationTest.java diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 2c6b9b55c0..e065701359 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -180,7 +180,7 @@ Implementation Notes: - Current concrete `room` digest fields include `id`, `zoneId`, `name`, `description`, `nameLocalizedVariantsJson`, and `descriptionLocalizedVariantsJson`. - Current concrete `room_exit` digest fields include `id`, `fromRoomId`, `toRoomId`, `direction`, and `cost`. - Current concrete `generation_rule` digest fields include `id`, `name`, `scopeType`, `scopeId`, and `value`; generation-rule mutations that carry a subtree scope must validate that declared scope, share the same scope epoch, and participate in `REPLACE_SCOPE` / `SEED_APPEND_ONLY` enforcement. -- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityTemplateId`, `spawnCount`, and `respawnDelaySeconds`. +- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityReference`, `spawnCount`, and `respawnDelaySeconds`. - Included objects: - version-scoped topology tables such as `region_template`, `zone_template`, `room_template`, `terrain_template`, `room_exit_template`, and equivalent normalized topology relations; @@ -197,7 +197,7 @@ Implementation Notes: - primary-key ordering within each table; - deterministic encoding for included semantic fields. - Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Null string values are canonicalized as empty strings before hashing. The current ordinary World digest schema version is `3`; scoped generation-rule metadata and tagged Entity spawn references are included in its deterministic projection. -- Spawn references use an explicit tagged representation: retained positive numeric private keys remain numeric evidence; canonical references retain exact non-nil tenant, Version and Entity template UUIDs. Mixed or partial representations are rejected. +- `entityReference` uses an explicit tagged representation. `RETAINED_PRIVATE_KEY` carries a positive private numeric key in `templateId`, encoded as a canonical decimal string; `CANONICAL_UUID` carries exact non-nil UUID values for `tenantId`, `versionId`, and `templateId`. Mixed or partial representations are rejected. - `digestSchemaVersion` must increment whenever included tables, field-selection rules, or canonical serialization semantics change. Publish gating fails closed if World Management cannot attest a digest consistent with this manifest. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index b34797bc5c..35789e269e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,9 +14,11 @@ The stage is component-only: PURE_UNVERIFIED input, STORED_PERMISSION_UNVERIFIED Focused definitions cover strict typed input/digest behavior, physical default-order parent34→stage40 preservation with original column bytes and xmin, independently updatable legacy rows, real guarded six-family store/replay, naked-write refusal and missing-checkpoint denial. The complete World service gate passed on parent `310532f10b8aa90d50e455e5ebc61a9c7e0b1cc2` with 273 fresh unit and 63 fresh physical PostgreSQL integration tests, zero failures/errors/skips, static checks and Markdown/link validation. This includes real guarded store/replay, source/version and installed34→stage40 retention plus legacy update concurrency. A follow-up whole service gate on parent `540fa37438615d7995552c08a5914545a3055d17` passed with 64 fresh PostgreSQL integrations and the same 273 unit results reused from the earlier gate, plus full static and documentation checks. It physically verifies direct current capture refusal without V19 history and schema-2 snapshot repository retention across V1006→V1007/V1007.1 with every original field, graph byte and xmin unchanged. That retention test uses explicitly controlled predecessor checkpoint/content metadata and real Source/Version/fence/snapshot repositories; it establishes storage retention, never the preceding capture producer, Account authorization or complete APPLIED synchronization. The normal carry to `55c23f79f47827f2926f8277ad894eada746def2` changed seven CI/Entity/tool/documentation paths and preserved all World/Common/protobuf postimages. Positive live frozen capture/readback and packaged fresh/restart runtime remain unrun. Earlier carrier proof does not qualify this stage. All genuine protected handoffs and Unit 1B holds remain open. +The graph/serializer review corrections passed the whole World service gate after the complete merged tooling carry from parent `1e22da1c29774c0be075a61bfbcd6252a945c0a3`: 294 unit tests passed in the preceding gate and were reused unchanged by the final gate; all 64 PostgreSQL integrations executed freshly in the final gate, with zero failures, errors or skips, plus static, formatting and Markdown/link checks. The corrected reader proves actual guarded canonical UUID spawn rows, distinct complete Entity reference tuples and retained numeric keys. Fresh snapshot bytes use `snapshotSchemaVersion=2`; immutable schema-1 bytes decode and re-encode unchanged, independently of digest schema 3. The real topology-store case also proves stable owner-binding bytes with a customized application mapper. These tests preserve the missing-V19 capture refusal and establish neither complete commit authority nor runtime activation. + ### Authored World Source Retention Status -The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. That historical source-retention proof excluded graph capture and used digest schema 2; the separate guarded owner stage above introduces graph/capture storage and the schema-3 writer with its own qualification boundary. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. That historical source-retention proof excluded graph capture and used digest schema 2; the separate guarded owner stage above introduces graph/capture storage and the schema-3 writer with its own qualification boundary. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical migration proof specifically for V1003 graph-snapshot installation is established; the later V1006-to-V1007/V1007.1 retention test is narrower. No deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. The earlier clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` remains attributable to that candidate: it reported 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in that gate, including the same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. At `42296c26c91459c229a6822c5a6fc81c8b0da4d1`, the focused World proof reports 263 unit cases, reused unchanged from the freshly executed unit suite at `c62de7bf127908cece54e6d97f4565b3147be9be`, including its SQL-state classification regression and 61 fresh PostgreSQL integration cases, with zero failures, errors, or skips. The PostgreSQL cases include timeout rollback, exact retry, and tighter-limit reset coverage. The clean World formatter/check/linkCheck run reported 10,822 links checked and the Markdown lint reported 550 files with zero issues. These results are focused local proof only; they do not establish a new combined Core/Game Design/World gate, full CI, external database application, runtime registration, or activation. @@ -48,7 +50,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; this retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | @@ -119,7 +121,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - `WORLD_GENERATION_SUBTREE` applies generated rooms, exits, generation rules, and spawn bindings in one declared subtree request. Entity references for spawn bindings are validated through the canonical Entity Management RPC. Design-time population writes World-owned declarative bindings only; Automation and Scripting cannot author template topology, bindings, or live entities as a generation side effect. - `GetDraftDesignDigest(versionId)` currently hashes the six implemented version-scoped families: regions, zones, rooms, room exits, generation rules including scoped metadata, and world-entity spawn bindings. The response does not expose a row-family manifest, so Game Design cannot independently prove that every applicable family was included; fail-closed family-manifest completeness remains a publish-gate requirement rather than a live check. - World room and topology caches are derived, versioned Class A state: room/world mutations and activation changes require explicit invalidation or refresh of affected keys, and reset/rebuild behavior must recompute from authoritative storage rather than treating TTL as correctness. The current implementation still has cache-hardening work around reset tolerance and complete event-driven invalidation. -- The applied-revision ledger now exists and is written transactionally with successful Draft mutations. The current World digest read still computes version-scoped template inputs and emits synthetic `appliedCommitId = "version:"`; the digest must derive a commit-level token only after that commit's complete revision set is durably applied. Revision-ledger identities remain replay and idempotency evidence, not the publish-convergence token. World currently emits digest schema `2`, while Game Design's live publish gate accepts only schema `1`, so full-version publish cannot admit the current World digest until coordinated schema adoption lands. Publish convergence also remains an obligation for newly introduced topology/generation families and separately exported navmesh/path-graph artifacts. +- The applied-revision ledger now exists and is written transactionally with successful Draft mutations. The current World digest read still computes version-scoped template inputs and emits synthetic `appliedCommitId = "version:"`; the digest must derive a commit-level token only after that commit's complete revision set is durably applied. Revision-ledger identities remain replay and idempotency evidence, not the publish-convergence token. The registered World `GetDraftDesignDigest` read emits schema `3`; the current Game Design publish gate supports World Management digest schema `2`, so full-version publish cannot admit the current World digest until coordinated schema adoption lands. The internal `WorldAuthoredGraphSnapshotCapture` remains unwired from publication and activation and records `CAPTURED_UNVERIFIED`; this read-interface mismatch does not qualify capture as publish evidence. Publish convergence also remains an obligation for newly introduced topology/generation families and separately exported navmesh/path-graph artifacts. ### Validation and Proof @@ -144,7 +146,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - Initial world-event scheduling is absent from the current prepare path despite being canonical lifecycle step 2. - Omitted optional terrain/population stages have no durable `SKIPPED_NOT_REQUIRED` outcome or operator-facing projection, so current lifecycle status cannot distinguish intentional omission from not-started or failed work. - The applied-revision ledger is live, but `GetDraftDesignDigest` still emits a synthetic version-derived `appliedCommitId` instead of deriving the highest commit whose complete revision set is durably applied. -- World digest schema `2` is not accepted by the current Game Design publish gate, which still accepts only schema `1`. +- World `GetDraftDesignDigest` emits schema `3`, while the current Game Design publish gate supports World Management digest schema `2`; coordinated schema adoption remains open. - The World digest response has no explicit row-family manifest, so the publish gate cannot independently detect an omitted applicable family even though the six current families are hashed. - Game Logic currently composes scope markers; the target causal floor plus actual World and Entity component-version identity is not implemented or proved. - Game Logic still exposes the legacy `READ_FENCE_MISMATCH` application code for participant `FAILED_PRECONDITION`; it must converge on target-state service rejection codes and keep returned-fence differences in the caller retry path. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java index 8956b4f184..218e4b4429 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java @@ -14,6 +14,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.UUID; import java.util.function.Function; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; import tools.jackson.core.JacksonException; @@ -25,13 +26,15 @@ /** Immutable World-owned value and codec for the six version-scoped authored content families. */ public final class WorldAuthoredGraph { - private static final int SNAPSHOT_SCHEMA_VERSION = 1; + private static final int SNAPSHOT_SCHEMA_VERSION = 2; private static final ObjectMapper STRICT_JSON_MAPPER = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .build(); + // Retained schema-1 snapshots keep their immutable byte representation on replay. + private final int snapshotSchemaVersion; private final List> regions; private final List> zones; private final List> rooms; @@ -46,6 +49,18 @@ public WorldAuthoredGraph( List> roomExits, List> generationRules, List> spawnBindings) { + this(SNAPSHOT_SCHEMA_VERSION, regions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private WorldAuthoredGraph( + int snapshotSchemaVersion, + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + this.snapshotSchemaVersion = snapshotSchemaVersion; this.regions = copyRows(regions, false); this.zones = copyRows(zones, false); this.rooms = copyRows(rooms, false); @@ -84,7 +99,7 @@ public List> spawnBindings() { public byte[] encode(ObjectMapper objectMapper) { Objects.requireNonNull(objectMapper, "objectMapper"); LinkedHashMap root = new LinkedHashMap<>(); - root.put("snapshotSchemaVersion", SNAPSHOT_SCHEMA_VERSION); + root.put("snapshotSchemaVersion", snapshotSchemaVersion); root.put("regions", regions); root.put("zones", zones); root.put("rooms", rooms); @@ -138,12 +153,14 @@ static WorldAuthoredGraph decode(byte[] encoded, ObjectMapper objectMapper) { "generationRules", "worldEntitySpawnBindings"); JsonNode schemaVersion = root.get("snapshotSchemaVersion"); - if (!schemaVersion.isInt() || schemaVersion.intValue() != SNAPSHOT_SCHEMA_VERSION) { + if (!schemaVersion.isInt() + || (schemaVersion.intValue() != 1 && schemaVersion.intValue() != SNAPSHOT_SCHEMA_VERSION)) { throw malformed("World authored graph snapshot schema version is unsupported"); } WorldAuthoredGraph graph = new WorldAuthoredGraph( + schemaVersion.intValue(), decodeRows(root.get("regions"), "regions", WorldAuthoredGraph::decodeRegion), decodeRows(root.get("zones"), "zones", WorldAuthoredGraph::decodeZone), decodeRows(root.get("rooms"), "rooms", WorldAuthoredGraph::decodeRoom), @@ -155,7 +172,7 @@ static WorldAuthoredGraph decode(byte[] encoded, ObjectMapper objectMapper) { decodeRows( root.get("worldEntitySpawnBindings"), "worldEntitySpawnBindings", - WorldAuthoredGraph::decodeSpawnBinding)); + row -> decodeSpawnBinding(row, schemaVersion.intValue()))); if (!Arrays.equals(graph.encode(objectMapper), original)) { throw malformed("World authored graph bytes are not in canonical encoding"); } @@ -280,14 +297,14 @@ private static LinkedHashMap decodeGenerationRule(JsonNode row) return decoded; } - private static LinkedHashMap decodeSpawnBinding(JsonNode row) { + private static LinkedHashMap decodeSpawnBinding(JsonNode row, int schemaVersion) { requireFields( row, "worldEntitySpawnBindings row", "id", "roomId", "entityTemplateType", - "entityTemplateId", + schemaVersion == 1 ? "entityTemplateId" : "entityReference", "spawnCount", "respawnDelaySeconds"); LinkedHashMap decoded = new LinkedHashMap<>(); @@ -298,8 +315,13 @@ private static LinkedHashMap decodeSpawnBinding(JsonNode row) { throw malformed("World authored graph worldEntitySpawnBindings row type is unsupported"); } decoded.put("entityTemplateType", entityType); - decoded.put( - "entityTemplateId", positiveLong(row, "entityTemplateId", "worldEntitySpawnBindings row")); + if (schemaVersion == 1) { + decoded.put( + "entityTemplateId", + positiveLong(row, "entityTemplateId", "worldEntitySpawnBindings row")); + } else { + decoded.put("entityReference", decodeEntityReference(row.get("entityReference"))); + } decoded.put("spawnCount", positiveInt(row, "spawnCount", "worldEntitySpawnBindings row")); decoded.put( "respawnDelaySeconds", @@ -307,6 +329,46 @@ private static LinkedHashMap decodeSpawnBinding(JsonNode row) { return decoded; } + private static LinkedHashMap decodeEntityReference(JsonNode reference) { + String label = "worldEntitySpawnBindings entityReference"; + requireObject(reference, label); + String kind = nonBlankString(reference, "kind", label); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("kind", kind); + if (kind.equals("RETAINED_PRIVATE_KEY")) { + requireFields(reference, label, "kind", "templateId"); + String templateId = nonBlankString(reference, "templateId", label); + try { + long numeric = Long.parseLong(templateId); + if (numeric <= 0L || !Long.toString(numeric).equals(templateId)) { + throw malformed("World authored graph retained Entity templateId is noncanonical"); + } + } catch (NumberFormatException exception) { + throw malformed( + "World authored graph retained Entity templateId is unsupported", exception); + } + decoded.put("templateId", templateId); + } else if (kind.equals("CANONICAL_UUID")) { + requireFields(reference, label, "kind", "tenantId", "versionId", "templateId"); + for (String field : List.of("tenantId", "versionId", "templateId")) { + String value = nonBlankString(reference, field, label); + try { + UUID uuid = UUID.fromString(value); + if (uuid.equals(new UUID(0L, 0L)) || !uuid.toString().equals(value)) { + throw malformed("World authored graph canonical Entity " + field + " is noncanonical"); + } + } catch (IllegalArgumentException exception) { + throw malformed( + "World authored graph canonical Entity " + field + " is unsupported", exception); + } + decoded.put(field, value); + } + } else { + throw malformed("World authored graph Entity reference kind is unsupported"); + } + return decoded; + } + private static void requireFields(JsonNode object, String label, String... fields) { requireObject(object, label); Set expected = Set.of(fields); @@ -409,7 +471,13 @@ private static SnapshotConflictException malformed(String message, Exception cau WorldAuthoredGraph withRegions(List> updatedRegions) { return new WorldAuthoredGraph( - updatedRegions, zones, rooms, roomExits, generationRules, spawnBindings); + snapshotSchemaVersion, + updatedRegions, + zones, + rooms, + roomExits, + generationRules, + spawnBindings); } private static List> copyRows( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java index 3409cc3665..67b89f6874 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; import org.jooq.DSLContext; import org.jooq.Field; @@ -54,6 +55,12 @@ final class WorldAuthoredGraphReader { private static final Field ENTITY_TEMPLATE_TYPE = field("entity_template_type", String.class); private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); + private static final Field ENTITY_CANONICAL_TENANT_ID = + field("entity_canonical_tenant_id", UUID.class); + private static final Field ENTITY_CANONICAL_VERSION_ID = + field("entity_canonical_version_id", UUID.class); + private static final Field ENTITY_CANONICAL_TEMPLATE_ID = + field("entity_canonical_template_id", UUID.class); private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); private static final Field RESPAWN_DELAY_SECONDS = field("respawn_delay_seconds", Integer.class); @@ -218,7 +225,7 @@ WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { rules.add(item); } - Set spawnKeys = new HashSet<>(); + Set> spawnKeys = new HashSet<>(); for (Record row : bindingRows) { requireExactScope(row, tenantKey, versionKey); long id = positive(row, ID, "world_entity_spawn_binding.id"); @@ -230,17 +237,16 @@ WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { "spawn room is missing or belongs to another tenant/Version"); } String entityType = required(row, ENTITY_TEMPLATE_TYPE); - Long entityId = required(row, ENTITY_TEMPLATE_ID); + Map entityReference = entityReference(row, id); Integer spawnCount = required(row, SPAWN_COUNT); Integer delay = required(row, RESPAWN_DELAY_SECONDS); if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) - || entityId <= 0L || spawnCount <= 0 || delay < 0) { throw incomplete( "world_entity_spawn_binding", id, "unsupported required spawn binding data"); } - String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; + List spawnKey = List.of(roomId, entityType, entityReference); if (!spawnKeys.add(spawnKey)) { throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); } @@ -248,7 +254,7 @@ WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { item.put("id", id); item.put("roomId", roomId); item.put("entityTemplateType", entityType); - item.put("entityTemplateId", entityId); + item.put("entityReference", entityReference); item.put("spawnCount", spawnCount); item.put("respawnDelaySeconds", delay); bindings.add(item); @@ -256,6 +262,37 @@ WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); } + private Map entityReference(Record row, long id) { + Long numeric = row.get(ENTITY_TEMPLATE_ID, Long.class); + UUID tenant = row.get(ENTITY_CANONICAL_TENANT_ID, UUID.class); + UUID version = row.get(ENTITY_CANONICAL_VERSION_ID, UUID.class); + UUID template = row.get(ENTITY_CANONICAL_TEMPLATE_ID, UUID.class); + LinkedHashMap reference = new LinkedHashMap<>(); + if (numeric != null) { + if (numeric <= 0L || tenant != null || version != null || template != null) { + throw incomplete("world_entity_spawn_binding", id, "mixed or nonpositive Entity reference"); + } + reference.put("kind", "RETAINED_PRIVATE_KEY"); + reference.put("templateId", numeric.toString()); + } else { + UUID nil = new UUID(0L, 0L); + if (tenant == null + || version == null + || template == null + || tenant.equals(nil) + || version.equals(nil) + || template.equals(nil)) { + throw incomplete( + "world_entity_spawn_binding", id, "partial or nil canonical Entity reference"); + } + reference.put("kind", "CANONICAL_UUID"); + reference.put("tenantId", tenant.toString()); + reference.put("versionId", version.toString()); + reference.put("templateId", template.toString()); + } + return reference; + } + private List fetch(Table table, long tenantKey, long versionKey) { List fetchedRows = dsl.selectFrom(table) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java index 3055518042..a772650cea 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -142,7 +142,8 @@ WorldCanonicalFrozenTopology capture(Request request) { } UUID captureId = UUID.randomUUID(); String freezeJson = JSON.writeValueAsString(request.freeze()); - String ownerJson = JSON.writeValueAsString(request.plan().ownerBinding()); + String ownerJson = + WorldDraftTopologyCommitRepository.ownerBindingJson(request.plan().ownerBinding()); byte[] result = result( captureId, @@ -202,7 +203,7 @@ private WorldCanonicalFrozenTopology find(Request supplied) { || !ownerBinding.equals(supplied.plan().ownerBinding()) || !freeze.equals(supplied.freeze()) || !bindingJson.equals(binding.canonicalJson()) - || !ownerJson.equals(JSON.writeValueAsString(ownerBinding)) + || !ownerJson.equals(WorldDraftTopologyCommitRepository.ownerBindingJson(ownerBinding)) || !freezeJson.equals(JSON.writeValueAsString(freeze))) { throw new ConflictException( "Frozen topology request was reused with changed complete input or checkpoint"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java index c7702ff47c..767a9c777e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -26,9 +26,12 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** Actual guarded six-family component storage; explicitly unwired, with private keys. */ public class WorldDraftTopologyCommitRepository { + private static final ObjectMapper OWNER_BINDING_JSON = JsonMapper.builder().build(); + private final DSLContext dsl; private final WorldDesignPublicationFenceRepository fence; private final ObjectMapper mapper; @@ -49,14 +52,18 @@ public Optional readCommitted( throw new ConflictException( "World complete storage readback requires no active caller transaction"); } - return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + return Optional.ofNullable(find(plan, ownerBindingJson(plan.ownerBinding()))); + } + + static String ownerBindingJson(WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + return OWNER_BINDING_JSON.writeValueAsString( + Objects.requireNonNull(ownerBinding, "ownerBinding")); } /** Caller already holds the exact shared V25 FROZEN owner lock; no writer is entered. */ WorldDraftTopologyCommitEvidence readUnderFrozenLock(WorldDraftTopologyCommitPlan plan) { requireTransaction(); - WorldDraftTopologyCommitEvidence stored = - find(plan, mapper.writeValueAsString(plan.ownerBinding())); + WorldDraftTopologyCommitEvidence stored = find(plan, ownerBindingJson(plan.ownerBinding())); if (stored == null) { throw new ConflictException("World frozen capture has no committed complete topology result"); } @@ -75,7 +82,7 @@ WorldCanonicalAuthoredGraph verifyImmutableBytes( WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { requireTransaction(); - String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + String ownerJson = ownerBindingJson(plan.ownerBinding()); WorldDraftTopologyCommitEvidence prior = find(plan, ownerJson); if (prior != null) { return prior; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java index 18f82c9a88..f67212d8ea 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java @@ -59,6 +59,8 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.SerializationFeature; +import tools.jackson.databind.json.JsonMapper; /** * Bounded native upgrade from the literal d7c8f84 World/Saga parent. External source and Version @@ -535,15 +537,24 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre contentDigest, 2, List.of()); - byte[] graphBytes = + var graphMapper = new tools.jackson.databind.ObjectMapper(); + byte[] freshGraphBytes = new WorldAuthoredGraphReader(dsl) .readAndValidateGraph(intake.localTenantKey(), version.localVersionKey()) - .encode(new tools.jackson.databind.ObjectMapper()); - assertThat(new String(graphBytes, StandardCharsets.UTF_8)) + .encode(graphMapper); + assertThat(new String(freshGraphBytes, StandardCharsets.UTF_8)) .isEqualTo( - "{\"snapshotSchemaVersion\":1,\"regions\":[],\"zones\":[],\"rooms\":[]," + "{\"snapshotSchemaVersion\":2,\"regions\":[],\"zones\":[],\"rooms\":[]," + "\"roomExits\":[],\"generationRules\":[]," + "\"worldEntitySpawnBindings\":[]}"); + // Retain actual predecessor bytes independently of the current schema-2 writer. + byte[] graphBytes = + ("{\"snapshotSchemaVersion\":1,\"regions\":[],\"zones\":[],\"rooms\":[]," + + "\"roomExits\":[],\"generationRules\":[]," + + "\"worldEntitySpawnBindings\":[]}") + .getBytes(StandardCharsets.UTF_8); + assertThat(WorldAuthoredGraph.decode(graphBytes, graphMapper).encode(graphMapper)) + .isEqualTo(graphBytes); var snapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); WorldAuthoredGraphSnapshot stored = Objects.requireNonNull( @@ -672,11 +683,106 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() new WorldDesignPublicationFenceRepository( dsl, new WorldAuthoredSourceIntakeRepository(dsl)); var mapper = new tools.jackson.databind.ObjectMapper(); - var topology = new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + var applicationMapper = + JsonMapper.builder().enable(SerializationFeature.INDENT_OUTPUT).build(); + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, applicationMapper); var plan = topologyPlan(intake, version); var stored = Objects.requireNonNull(write.execute(status -> topology.store(plan))); assertThat(stored.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + String storedOwnerBindingJson = + dsl.fetchSingle( + "SELECT owner_binding_json FROM world_topology_draft_commit WHERE request_id = ?", + plan.binding().requestId()) + .get("owner_binding_json", String.class); + assertThat(storedOwnerBindingJson) + .isEqualTo(WorldDraftTopologyCommitRepository.ownerBindingJson(plan.ownerBinding())) + .isNotEqualTo(applicationMapper.writeValueAsString(plan.ownerBinding())); assertThat(topology.readCommitted(plan)).isPresent(); + // Exercise the snapshot reader against actual V1005 canonical spawn storage. This is + // graph/codec proof only: it does not supply the missing V19 complete-commit history. + var authored = + Objects.requireNonNull( + write.execute( + status -> + new WorldAuthoredGraphReader(dsl) + .readAndValidateGraph( + intake.localTenantKey(), version.localVersionKey()))); + var spawnRow = + dsl.fetchSingle( + "SELECT entity_template_id, entity_canonical_tenant_id, entity_canonical_version_id, " + + "entity_canonical_template_id FROM world_entity_spawn_binding " + + "WHERE tenant_id = ? AND version_id = ?", + intake.localTenantKey(), + version.localVersionKey()); + assertThat(spawnRow.get("entity_template_id")).isNull(); + assertThat(authored.spawnBindings()).hasSize(1); + assertThat(authored.spawnBindings().getFirst().get("entityReference")) + .isEqualTo( + Map.of( + "kind", "CANONICAL_UUID", + "tenantId", spawnRow.get("entity_canonical_tenant_id", UUID.class).toString(), + "versionId", spawnRow.get("entity_canonical_version_id", UUID.class).toString(), + "templateId", + spawnRow.get("entity_canonical_template_id", UUID.class).toString())); + byte[] authoredBytes = authored.encode(mapper); + assertThat(mapper.readTree(authoredBytes).get("snapshotSchemaVersion").intValue()) + .isEqualTo(2); + assertThat(WorldAuthoredGraph.decode(authoredBytes, mapper).encode(mapper)) + .isEqualTo(authoredBytes); + // An independent legacy tenant exercises both storage representations and proves that + // canonical duplicate identity includes the tenant and Version, not only the template UUID. + // These ordinary unclaimed rows do not represent a canonical authored-source capture. + long legacyRegion = + dsl.fetchSingle( + "INSERT INTO region (tenant_id, version_id, name, generation_seed) " + + "VALUES (7002, 12, 'Reader region', 42) RETURNING id") + .get(0, Long.class); + long legacyZone = + dsl.fetchSingle( + "INSERT INTO zone (tenant_id, version_id, region_id, name) " + + "VALUES (7002, 12, ?, 'Reader zone') RETURNING id", + legacyRegion) + .get(0, Long.class); + long legacyRoom = + dsl.fetchSingle( + "INSERT INTO room (tenant_id, version_id, zone_id, name) " + + "VALUES (7002, 12, ?, 'Reader room') RETURNING id", + legacyZone) + .get(0, Long.class); + UUID entityTenant = UUID.randomUUID(); + UUID entityVersion = UUID.randomUUID(); + UUID entityTemplate = UUID.randomUUID(); + for (var reference : + List.of( + List.of(entityTenant, entityVersion, entityTemplate), + List.of(UUID.randomUUID(), entityVersion, entityTemplate), + List.of(entityTenant, UUID.randomUUID(), entityTemplate))) { + dsl.execute( + "INSERT INTO world_entity_spawn_binding (tenant_id, version_id, room_id, " + + "entity_template_type, entity_template_id, entity_canonical_tenant_id, " + + "entity_canonical_version_id, entity_canonical_template_id) " + + "VALUES (7002, 12, ?, 'NPC', NULL, ?, ?, ?)", + legacyRoom, + reference.get(0), + reference.get(1), + reference.get(2)); + } + dsl.execute( + "INSERT INTO world_entity_spawn_binding (tenant_id, version_id, room_id, " + + "entity_template_type, entity_template_id) VALUES (7002, 12, ?, 'NPC', ?)", + legacyRoom, + Long.MAX_VALUE); + var legacyGraph = + Objects.requireNonNull( + write.execute( + status -> new WorldAuthoredGraphReader(dsl).readAndValidateGraph(7002L, 12L))); + assertThat(legacyGraph.spawnBindings()).hasSize(4); + assertThat(legacyGraph.spawnBindings().getLast().get("entityReference")) + .isEqualTo( + Map.of("kind", "RETAINED_PRIVATE_KEY", "templateId", Long.toString(Long.MAX_VALUE))); + byte[] legacyGraphBytes = legacyGraph.encode(mapper); + assertThat(WorldAuthoredGraph.decode(legacyGraphBytes, mapper).encode(mapper)) + .isEqualTo(legacyGraphBytes); var replay = Objects.requireNonNull(write.execute(status -> topology.store(plan))); assertThat(replay.graphBytes()).isEqualTo(stored.graphBytes()); assertThat(replay.resultBytes()).isEqualTo(stored.resultBytes()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java new file mode 100644 index 0000000000..882993f57e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import tools.jackson.databind.ObjectMapper; + +class WorldAuthoredGraphCodecTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String TENANT = "11111111-1111-1111-1111-111111111111"; + private static final String VERSION = "22222222-2222-2222-2222-222222222222"; + private static final String TEMPLATE = "33333333-3333-3333-3333-333333333333"; + private static final String CANONICAL_REFERENCE = + "{\"kind\":\"CANONICAL_UUID\",\"tenantId\":\"" + + TENANT + + "\",\"versionId\":\"" + + VERSION + + "\",\"templateId\":\"" + + TEMPLATE + + "\"}"; + + @Test + void freshSnapshotsUseSchemaTwoAndRetainTheCompleteCanonicalEntityTuple() { + LinkedHashMap reference = new LinkedHashMap<>(); + reference.put("kind", "CANONICAL_UUID"); + reference.put("tenantId", TENANT); + reference.put("versionId", VERSION); + reference.put("templateId", TEMPLATE); + byte[] encoded = freshGraph(reference).encode(MAPPER); + + assertThat(encoded).isEqualTo(snapshot(2, "\"entityReference\":" + CANONICAL_REFERENCE)); + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(encoded, MAPPER); + assertThat(decoded.spawnBindings().getFirst().get("entityReference")).isEqualTo(reference); + assertThat(decoded.encode(MAPPER)).isEqualTo(encoded); + assertThat(decoded.withRegions(List.of()).encode(MAPPER)).isEqualTo(encoded); + } + + @Test + void freshSnapshotsTagRetainedPrivateKeysWithoutLosingLongPrecision() { + LinkedHashMap reference = new LinkedHashMap<>(); + reference.put("kind", "RETAINED_PRIVATE_KEY"); + reference.put("templateId", Long.toString(Long.MAX_VALUE)); + byte[] encoded = freshGraph(reference).encode(MAPPER); + + assertThat(encoded) + .isEqualTo( + snapshot( + 2, + "\"entityReference\":{\"kind\":\"RETAINED_PRIVATE_KEY\"," + + "\"templateId\":\"9223372036854775807\"}")); + assertThat(WorldAuthoredGraph.decode(encoded, MAPPER).encode(MAPPER)).isEqualTo(encoded); + } + + @Test + void retainedSchemaOneNumericSnapshotsReencodeWithExactlyTheirOriginalBytes() { + byte[] retained = snapshot(1, "\"entityTemplateId\":9223372036854775807"); + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(retained, MAPPER); + + assertThat(decoded.spawnBindings().getFirst().get("entityTemplateId")) + .isEqualTo(Long.MAX_VALUE); + assertThat(decoded.encode(MAPPER)).isEqualTo(retained); + assertThat(decoded.withRegions(List.of()).encode(MAPPER)).isEqualTo(retained); + } + + @ParameterizedTest + @MethodSource("invalidReferences") + void schemaTwoRejectsPartialMixedUnknownAndNoncanonicalReferences(String reference) { + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode(snapshot(2, "\"entityReference\":" + reference), MAPPER)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + } + + private static Stream invalidReferences() { + return Stream.of( + "null", + "{}", + "{\"kind\":\"UNKNOWN\",\"templateId\":\"1\"}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":1}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"0\"}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"-1\"}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"01\"}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"9223372036854775808\"}", + "{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"1\",\"tenantId\":\"" + TENANT + "\"}", + "{\"kind\":\"CANONICAL_UUID\",\"templateId\":\"" + TEMPLATE + "\"}", + CANONICAL_REFERENCE.replace("\"tenantId\":\"" + TENANT + "\"", "\"tenantId\":null"), + CANONICAL_REFERENCE.replace(VERSION, "00000000-0000-0000-0000-000000000000"), + CANONICAL_REFERENCE.replace(TEMPLATE, "3-3-3-3-3"), + CANONICAL_REFERENCE.replace(TENANT, "not-a-uuid"), + CANONICAL_REFERENCE.replace(TENANT, "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"), + CANONICAL_REFERENCE.replace("}", ",\"entityTemplateId\":1}")); + } + + @Test + void snapshotVersionsDoNotAcceptEachOthersSpawnRepresentationOrDigestSchemaVersion() { + assertThatThrownBy( + () -> WorldAuthoredGraph.decode(snapshot(2, "\"entityTemplateId\":1"), MAPPER)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + snapshot(1, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + snapshot(3, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + } + + private static WorldAuthoredGraph freshGraph(Map reference) { + LinkedHashMap binding = new LinkedHashMap<>(); + binding.put("id", 7L); + binding.put("roomId", 8L); + binding.put("entityTemplateType", "NPC"); + binding.put("entityReference", reference); + binding.put("spawnCount", 2); + binding.put("respawnDelaySeconds", 0); + return new WorldAuthoredGraph( + List.of(), List.of(), List.of(), List.of(), List.of(), List.of(binding)); + } + + private static byte[] snapshot(int version, String referenceField) { + return ("{\"snapshotSchemaVersion\":" + + version + + ",\"regions\":[],\"zones\":[],\"rooms\":[],\"roomExits\":[],\"generationRules\":[]," + + "\"worldEntitySpawnBindings\":[{\"id\":7,\"roomId\":8,\"entityTemplateType\":\"NPC\"," + + referenceField + + ",\"spawnCount\":2,\"respawnDelaySeconds\":0}]}") + .getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOwnerBindingSerializationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOwnerBindingSerializationTest.java new file mode 100644 index 0000000000..0cb8462cd4 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOwnerBindingSerializationTest.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.SerializationFeature; +import tools.jackson.databind.json.JsonMapper; + +class WorldOwnerBindingSerializationTest { + private static final OwnerBinding OWNER_BINDING = + new OwnerBinding( + "firemud", + UUID.fromString("00000000-0000-0000-0000-000000000001"), + UUID.fromString("00000000-0000-0000-0000-000000000002"), + UUID.fromString("00000000-0000-0000-0000-000000000003"), + 42L, + UUID.fromString("00000000-0000-0000-0000-000000000004"), + UUID.fromString("00000000-0000-0000-0000-000000000005"), + "sha256:" + "1".repeat(64), + UUID.fromString("00000000-0000-0000-0000-000000000006"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + + @Test + void ownerBytesUseStableDefaultSerializationRegardlessOfApplicationMapperConfiguration() { + var applicationMapper = JsonMapper.builder().enable(SerializationFeature.INDENT_OUTPUT).build(); + + String serializedOwner = WorldDraftTopologyCommitRepository.ownerBindingJson(OWNER_BINDING); + + assertThat(serializedOwner) + .isEqualTo( + "{\"targetNamespace\":\"firemud\"," + + "\"canonicalTenantId\":\"00000000-0000-0000-0000-000000000001\"," + + "\"canonicalVersionId\":\"00000000-0000-0000-0000-000000000002\"," + + "\"versionIdentityOperationId\":\"00000000-0000-0000-0000-000000000003\"," + + "\"gameDesignVersionId\":42," + + "\"intakeRequestId\":\"00000000-0000-0000-0000-000000000004\"," + + "\"intakeOperationId\":\"00000000-0000-0000-0000-000000000005\"," + + "\"intakeRequestDigest\":\"sha256:" + + "1111111111111111111111111111111111111111111111111111111111111111\"," + + "\"sourceOperationId\":\"00000000-0000-0000-0000-000000000006\"," + + "\"sourceEvidenceDigest\":\"sha256:" + + "2222222222222222222222222222222222222222222222222222222222222222\"," + + "\"intakeReceiptDigest\":\"sha256:" + + "3333333333333333333333333333333333333333333333333333333333333333\"}"); + assertThat(applicationMapper.writeValueAsString(OWNER_BINDING)).isNotEqualTo(serializedOwner); + } +} From a9223d8c7de47444743b038c02b2d7127ec4265c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:30:10 +1300 Subject: [PATCH 3/7] Align publication gate with World digest schema three --- ...ame-authoring-publishing-and-activation.md | 4 + .../service/impl/PublishGateServiceImpl.java | 2 +- .../client/WorldManagementClientTest.java | 172 ++++++++++++++++++ .../CompleteLaunchBindingServiceImplTest.java | 38 ++++ .../impl/PublishGateServiceImplTest.java | 19 +- 5 files changed, 225 insertions(+), 10 deletions(-) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java 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 4244057987..1cca61a82e 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,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### World digest consumer convergence + +The ordinary World producer emits digest schema 3 for its tagged Entity-reference projection. The full-Version publication gate now requires that schema while preserving exact participant sets, scope, successful owner results, one shared applied commit and independent participant schemas. The existing complete-launch reader already selects World schema 3 through its shared attestation contract; schema 2 and unselected closure schema 4 are rejected for this boundary. The unchanged World client carries the exact owner response rather than rewriting its digest/schema, and checks tenant and typed Version scope. On the prepared patch based on `3ae5fffd4aec52101739c78d89cd6bd0ce5f9935`, 32 focused gate, caller and complete-launch unit cases freshly passed with zero failures, errors or skips; affected formatting, main/test static analysis and documentation checks also passed. No physical database or packaged runtime gate was run for this one-constant consumer correction. These source checks do not establish authenticated complete-commit producer execution, selected Human publication, or a genuine Gameplay handoff; controlled client responses are unit inputs. + 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 diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 4155e3b6d1..a70eb5a7f4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -24,7 +24,7 @@ public class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = Map.of( - PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, + PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, PublishParticipantKey.ENTITY_MANAGEMENT.name(), 1, PublishParticipantKey.GAME_LOGIC.name(), 1, PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java new file mode 100644 index 0000000000..751407ebb9 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.gamedesign.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.time.LocalDateTime; +import java.util.List; +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.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl; +import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Wire mapping and gate proof with a controlled World response, not live producer authority. */ +class WorldManagementClientTest { + private static final PublicationDigestRequestBinding BINDING = + PublicationDigestRequestBinding.full("tenant-é", "7", "request-é"); + + @Test + void exactWorldSchemaThreeResponseReachesGateWithoutRewritingItsEvidence() throws Exception { + var stub = mock(WorldManagementServiceGrpc.WorldManagementServiceBlockingStub.class); + var response = response(3).build(); + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))).thenReturn(response); + var client = client(stub); + + var digest = client.getDraftDesignDigestForVersion(BINDING); + + assertThat(digest.succeeded()).isTrue(); + assertThat(digest.digestSchemaVersion()).isEqualTo(3); + assertThat(digest.contentDigest()).isEqualTo(response.getContentDigest()); + assertThat(digest.appliedCommitId()).isEqualTo(response.getAppliedCommitId()); + gate().assertGatePassed(version(), participants(digest)); + var request = ArgumentCaptor.forClass(GetDraftDesignDigestRequest.class); + verify(stub).getDraftDesignDigest(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo(BINDING.tenantId()); + assertThat(request.getValue().getVersionId()).isEqualTo(BINDING.versionId()); + assertThat(request.getValue().getPublishRequestId()).isEqualTo(BINDING.publishRequestId()); + assertThat(request.getValue().getDerivedWorkflowIdentity()) + .isEqualTo(BINDING.derivedWorkflowIdentity()); + assertThat(request.getValue().getRequestDigest()).isEqualTo(BINDING.requestDigest()); + } + + @Test + void obsoleteAndUnselectedWorldFramesRemainUnchangedAndAreRejectedByGate() throws Exception { + var stub = mock(WorldManagementServiceGrpc.WorldManagementServiceBlockingStub.class); + var client = client(stub); + for (int schema : List.of(2, 4)) { + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response(schema).build()); + var digest = client.getDraftDesignDigestForVersion(BINDING); + assertThat(digest.digestSchemaVersion()).isEqualTo(schema); + assertThatThrownBy(() -> gate().assertGatePassed(version(), participants(digest))) + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); + } + } + + @Test + void schemaThreeCannotBypassExactScopeOrOneSharedCommit() throws Exception { + var stub = mock(WorldManagementServiceGrpc.WorldManagementServiceBlockingStub.class); + var client = client(stub); + for (var mismatch : + List.of( + response(3).setTenantId("other"), + response(3).setVersionId("8"), + response(3).setBaseVersionId("6"))) { + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(mismatch.build()); + var digest = client.getDraftDesignDigestForVersion(BINDING); + assertThat(digest.succeeded()).isFalse(); + assertThat(digest.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH"); + } + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response(3).setAppliedCommitId("other-commit").build()); + var digest = client.getDraftDesignDigestForVersion(BINDING); + assertThatThrownBy(() -> gate().assertGatePassed(version(), participants(digest))) + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.APPLIED_COMMIT_MISMATCH)); + } + + private static GetDraftDesignDigestResponse.Builder response(int schema) { + return GetDraftDesignDigestResponse.newBuilder() + .setTenantId(BINDING.tenantId()) + .setVersionId(BINDING.versionId()) + .setAppliedCommitId("commit-7") + .setContentDigest("a".repeat(64)) + .setDigestSchemaVersion(schema); + } + + private static List participants(PublishParticipantDigestDto world) { + return List.of( + world, + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "7", "commit-7", "entity", 1, null, null), + new PublishParticipantDigestDto("GAME_LOGIC", "7", "commit-7", "logic", 1, null, null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", "7", "commit-7", "script", 5, null, null), + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", "7", "commit-7", "design", 1, null, null)); + } + + private static PublishGateServiceImpl gate() { + return new PublishGateServiceImpl(null, null, null, null, null); + } + + private static VersionDto version() { + return new VersionDto( + 7L, + BINDING.tenantId(), + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + + private static TestWorldManagementClient client( + WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(true); + var client = new TestWorldManagementClient(properties, stub); + client.init(); + return client; + } + + private static final class TestWorldManagementClient extends WorldManagementClient { + private final WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub; + + private TestWorldManagementClient( + CommonGrpcClientProperties properties, + WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub) { + super( + new ServiceEndpointsProperties(), + properties, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + this.stub = stub; + } + + @Override + protected WorldManagementServiceGrpc.WorldManagementServiceBlockingStub buildStub( + ManagedChannel channel) { + return applyStubCustomizer(stub); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index b0b2132e96..714e30c47f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -56,6 +56,44 @@ void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads( verifyReadOnlyCallsOnly(); } + @Test + void completeLaunchBindingRejectsObsoleteOrUnselectedWorldSchemas() { + for (int schema : List.of(2, 4)) { + var participants = new java.util.ArrayList<>(bundle.participantDigests()); + var world = participants.getFirst(); + participants.set( + 0, + new PublishParticipantDigestDto( + world.participantKey(), + world.scopeValue(), + world.baseVersionId(), + world.appliedCommitId(), + world.contentDigest(), + schema, + world.abilitySchemaDigest(), + world.errorCode(), + world.errorMessage())); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + participants, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied("PARTICIPANT_EVIDENCE_INVALID"); + } + } + @Test void selectorV2RejectsLegacyGameDesignControlPlaneParticipantSchema() throws Exception { var selector = selectorEvidence(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 8f59504bac..1c54a243b1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -68,7 +68,7 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null)); + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null)); when(entityManagementClient.getDraftDesignDigestForVersion( any(PublicationDigestRequestBinding.class))) .thenReturn( @@ -120,7 +120,7 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -140,7 +140,7 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { } @Test - void fullVersionGateFailsClosedForUnsupportedSchema() { + void fullVersionGateRejectsObsoleteWorldDigestSchema() { VersionDto version = new VersionDto( 7L, @@ -157,7 +157,7 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -171,6 +171,7 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { assertThrows( PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, thrown.failureCode()); + assertTrue(thrown.getMessage().contains("WORLD_MANAGEMENT")); } @Test @@ -191,7 +192,7 @@ void fullVersionGateChecksEachParticipantAgainstItsOwnDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -227,7 +228,7 @@ void fullVersionGateRejectsObsoleteAutomationDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -316,9 +317,9 @@ void fullVersionGateFailsClosedForDuplicateParticipantKey() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -353,7 +354,7 @@ void fullVersionGateFailsClosedForNullParticipantObservation() { List digests = java.util.Arrays.asList( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), null, new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), From 54afe86b01e5c62fd1b5bf631553d26d019e1e81 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:57:41 +1300 Subject: [PATCH 4/7] Stabilize World evidence replay and verify frozen capture guards --- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 2 +- .../world-runtime-and-movement.md | 8 +- .../WorldDraftDesignDigestServiceImpl.java | 5 +- .../WorldAuthoredGraphSnapshotCapture.java | 19 +- .../WorldDraftTopologyCommitRepository.java | 13 +- ...edGraphCapturePostgresIntegrationTest.java | 229 +++++++++++++++++- ...WorldDraftDesignDigestServiceImplTest.java | 13 +- ...GraphSnapshotCaptureSerializationTest.java | 21 ++ 9 files changed, 273 insertions(+), 39 deletions(-) create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCaptureSerializationTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 45ab4d5d03..27644453f1 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. An unpublished component-owner candidate now includes graph capture and the ordinary schema-3 digest writer; its checkpoint producer and focused proof remain incomplete, as recorded in the tracker. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The source-retention cut itself does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. A separate component-owner candidate includes graph capture and the ordinary schema-3 digest writer; its checkpoint producer and focused proof remain incomplete, as recorded in the tracker. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index e065701359..6bab85e238 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). An unpublished guarded graph/capture candidate includes the ordinary schema-3 digest writer; its exact checkpoint producer and focused proof are incomplete and are recorded in the tracker. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its source-retention migrations are `V23.1` and `V24`–`V27.2`; the guarded component-owner stage adds `V1003`–`V1007.1`. These forward-only migrations preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The guarded component-owner candidate includes graph capture and the ordinary schema-3 digest writer; its exact checkpoint producer remains unqualified, and focused component proof is recorded in the tracker. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 35789e269e..68e6241755 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -12,7 +12,7 @@ The World owner stage carries immutable donor migrations V1003–V1007 for guard The stage is component-only: PURE_UNVERIFIED input, STORED_PERMISSION_UNVERIFIED topology and CAPTURED_UNVERIFIED capture do not establish Account authorization, APPLIED synchronization, selected inbound closure, release, runtime preparation, activation or operational-region authority. The ordinary digest retains its synthetic `version:` token. Live canonical frozen capture remains unqualified: it requires the original complete commit UUID, while the authenticated Game Design complete-commit/head and expected World revision-vector producer is absent. Individual APPLIED V19 rows lack complete-commit and head-order evidence; stored topology cannot supply it. The frozen request keeps exact checkpoint equality and fails closed without this producer. Source/Version upstream test evidence is explicitly controlled. -Focused definitions cover strict typed input/digest behavior, physical default-order parent34→stage40 preservation with original column bytes and xmin, independently updatable legacy rows, real guarded six-family store/replay, naked-write refusal and missing-checkpoint denial. The complete World service gate passed on parent `310532f10b8aa90d50e455e5ebc61a9c7e0b1cc2` with 273 fresh unit and 63 fresh physical PostgreSQL integration tests, zero failures/errors/skips, static checks and Markdown/link validation. This includes real guarded store/replay, source/version and installed34→stage40 retention plus legacy update concurrency. A follow-up whole service gate on parent `540fa37438615d7995552c08a5914545a3055d17` passed with 64 fresh PostgreSQL integrations and the same 273 unit results reused from the earlier gate, plus full static and documentation checks. It physically verifies direct current capture refusal without V19 history and schema-2 snapshot repository retention across V1006→V1007/V1007.1 with every original field, graph byte and xmin unchanged. That retention test uses explicitly controlled predecessor checkpoint/content metadata and real Source/Version/fence/snapshot repositories; it establishes storage retention, never the preceding capture producer, Account authorization or complete APPLIED synchronization. The normal carry to `55c23f79f47827f2926f8277ad894eada746def2` changed seven CI/Entity/tool/documentation paths and preserved all World/Common/protobuf postimages. Positive live frozen capture/readback and packaged fresh/restart runtime remain unrun. Earlier carrier proof does not qualify this stage. All genuine protected handoffs and Unit 1B holds remain open. +Focused definitions cover strict typed input/digest behavior, physical default-order parent34→stage40 preservation with original column bytes and xmin, independently updatable legacy rows, real guarded six-family store/replay, naked-write refusal and missing-checkpoint denial. The complete World service gate passed on parent `310532f10b8aa90d50e455e5ebc61a9c7e0b1cc2` with 273 fresh unit and 63 fresh physical PostgreSQL integration tests, zero failures/errors/skips, static checks and Markdown/link validation. This includes real guarded store/replay, source/version and installed34→stage40 retention plus legacy update concurrency. A later gate on parent `540fa37438615d7995552c08a5914545a3055d17` added the snapshot-retention case and passed with 64 fresh PostgreSQL integrations and the same 273 unit results reused from the earlier gate, plus full static and documentation checks. It physically verifies direct current capture refusal without V19 history and schema-2 snapshot repository retention across V1006→V1007/V1007.1 with every original field, graph byte and xmin unchanged. That retention test uses explicitly controlled predecessor checkpoint/content metadata and real Source/Version/fence/snapshot repositories; it establishes storage retention, never the preceding capture producer, Account authorization or complete APPLIED synchronization. The normal carry to `55c23f79f47827f2926f8277ad894eada746def2` changed seven CI/Entity/tool/documentation paths and preserved all World/Common/protobuf postimages. Positive live frozen capture/readback and packaged fresh/restart runtime remain unrun. Earlier carrier proof does not qualify this stage. All genuine protected handoffs and Unit 1B holds remain open. The graph/serializer review corrections passed the whole World service gate after the complete merged tooling carry from parent `1e22da1c29774c0be075a61bfbcd6252a945c0a3`: 294 unit tests passed in the preceding gate and were reused unchanged by the final gate; all 64 PostgreSQL integrations executed freshly in the final gate, with zero failures, errors or skips, plus static, formatting and Markdown/link checks. The corrected reader proves actual guarded canonical UUID spawn rows, distinct complete Entity reference tuples and retained numeric keys. Fresh snapshot bytes use `snapshotSchemaVersion=2`; immutable schema-1 bytes decode and re-encode unchanged, independently of digest schema 3. The real topology-store case also proves stable owner-binding bytes with a customized application mapper. These tests preserve the missing-V19 capture refusal and establish neither complete commit authority nor runtime activation. @@ -34,6 +34,8 @@ This tracker is the permanent reader-facing implementation record for world runt The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Its separate World launch-evidence provider rereads the immutable capability and receipt, verifies the caller and both recipient pins, and reads the real Game Design descriptor before World mutation. World persists a binding digest and original preparing epoch on `world_instance`; exact ACTIVE replay at that epoch with identical evidence does not cause another transition. Historical original-source compositional proof for the bounded fixture lifecycle was accepted at `f330c8721824d063a5eba09afd5388631ae184b9`: unchanged `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` World socket (2), PostgreSQL (3), provider (5), and lifecycle unit (22) cases passed without skips, complemented by rebuilt positive Smoke run `38174536549` on merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`). The current private reconstruction has separate consolidated local checks: its two authenticated socket cases pass, while three World PostgreSQL cases skip without Docker and rebuilt packaged Smoke/restart remain unrun. Historical Smoke does not prove startup refusal (skipped), packaged process restart, per-RPC counters, later protected activation, or hold race/restart; exact provenance and complementary producer/denial proof are recorded in [the Game Design fixture status](game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [run-owned launch-evidence contract](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). +The subsequent World/Game Design review-fix gate verifies fixed immutable graph/result/evidence serialization across application-mapper changes and direct PostgreSQL frozen-capture rejection/immutability guards. All 295 World unit cases passed in the preceding combined gate and were reused by the final World gate; all 64 PostgreSQL integrations ran freshly in that final gate, with no failures, errors or skips, plus World and affected Game Design static/formatting checks and Markdown/link validation. The Game Design gate passed 507 fresh unit cases, including the controlled schema-3 wire/gate and schema-2/4 refusal cases. Its broader PostgreSQL run selected 136 cases: 120 passed and 16 failed before assertions because a fixture endpoint refused connections; the cause remains unknown, so the full Game Design physical gate is not established by this run. This component proof does not qualify the missing complete-commit producer, positive live frozen capture, packaged runtime or activation. + ## Packet 4 Status and Proof Gaps - `GR-2.1` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) requires world runtime state to distinguish the durable playable-state namespace and `playableStateScope` from a disposable instance and to classify owner data before replacement. Current world instance and lifecycle evidence remains partial; no exhaustive S1/S2/S3 mapping or cleanup proof is claimed. @@ -121,7 +123,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - `WORLD_GENERATION_SUBTREE` applies generated rooms, exits, generation rules, and spawn bindings in one declared subtree request. Entity references for spawn bindings are validated through the canonical Entity Management RPC. Design-time population writes World-owned declarative bindings only; Automation and Scripting cannot author template topology, bindings, or live entities as a generation side effect. - `GetDraftDesignDigest(versionId)` currently hashes the six implemented version-scoped families: regions, zones, rooms, room exits, generation rules including scoped metadata, and world-entity spawn bindings. The response does not expose a row-family manifest, so Game Design cannot independently prove that every applicable family was included; fail-closed family-manifest completeness remains a publish-gate requirement rather than a live check. - World room and topology caches are derived, versioned Class A state: room/world mutations and activation changes require explicit invalidation or refresh of affected keys, and reset/rebuild behavior must recompute from authoritative storage rather than treating TTL as correctness. The current implementation still has cache-hardening work around reset tolerance and complete event-driven invalidation. -- The applied-revision ledger now exists and is written transactionally with successful Draft mutations. The current World digest read still computes version-scoped template inputs and emits synthetic `appliedCommitId = "version:"`; the digest must derive a commit-level token only after that commit's complete revision set is durably applied. Revision-ledger identities remain replay and idempotency evidence, not the publish-convergence token. The registered World `GetDraftDesignDigest` read emits schema `3`; the current Game Design publish gate supports World Management digest schema `2`, so full-version publish cannot admit the current World digest until coordinated schema adoption lands. The internal `WorldAuthoredGraphSnapshotCapture` remains unwired from publication and activation and records `CAPTURED_UNVERIFIED`; this read-interface mismatch does not qualify capture as publish evidence. Publish convergence also remains an obligation for newly introduced topology/generation families and separately exported navmesh/path-graph artifacts. +- The applied-revision ledger now exists and is written transactionally with successful Draft mutations. The current World digest read still computes version-scoped template inputs and emits synthetic `appliedCommitId = "version:"`; the digest must derive a commit-level token only after that commit's complete revision set is durably applied. Revision-ledger identities remain replay and idempotency evidence, not the publish-convergence token. The registered World `GetDraftDesignDigest` read emits schema `3`, and the Game Design full-Version gate now requires that schema without relaxing exact scope, participant or shared-commit checks. The internal `WorldAuthoredGraphSnapshotCapture` remains unwired from publication and activation and records `CAPTURED_UNVERIFIED`; aligned read schemas do not qualify capture as publish evidence. Publish convergence also remains an obligation for newly introduced topology/generation families and separately exported navmesh/path-graph artifacts. ### Validation and Proof @@ -146,7 +148,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - Initial world-event scheduling is absent from the current prepare path despite being canonical lifecycle step 2. - Omitted optional terrain/population stages have no durable `SKIPPED_NOT_REQUIRED` outcome or operator-facing projection, so current lifecycle status cannot distinguish intentional omission from not-started or failed work. - The applied-revision ledger is live, but `GetDraftDesignDigest` still emits a synthetic version-derived `appliedCommitId` instead of deriving the highest commit whose complete revision set is durably applied. -- World `GetDraftDesignDigest` emits schema `3`, while the current Game Design publish gate supports World Management digest schema `2`; coordinated schema adoption remains open. +- World digest schema `3` and its Game Design gate are aligned; the synthetic World applied-commit token and missing synchronized complete-commit producer remain open. - The World digest response has no explicit row-family manifest, so the publish gate cannot independently detect an omitted applicable family even though the six current families are hashed. - Game Logic currently composes scope markers; the target causal floor plus actual World and Entity component-version identity is not implemented or proved. - Game Logic still exposes the legacy `READ_FENCE_MISMATCH` application code for participant `FAILED_PRECONDITION`; it must converge on target-state service rejection codes and keep returned-fence differences in the caller retry path. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index cc77707130..098d0ddee7 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -7,7 +7,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.TreeMap; import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; @@ -44,15 +43,13 @@ public WorldDraftDesignDigestServiceImpl( RoomRepository roomRepository, RoomExitRepository roomExitRepository, GenerationRuleRepository generationRuleRepository, - WorldEntitySpawnBindingRepository worldEntitySpawnBindingRepository, - ObjectMapper objectMapper) { + WorldEntitySpawnBindingRepository worldEntitySpawnBindingRepository) { this.regionRepository = regionRepository; this.zoneRepository = zoneRepository; this.roomRepository = roomRepository; this.roomExitRepository = roomExitRepository; this.generationRuleRepository = generationRuleRepository; this.worldEntitySpawnBindingRepository = worldEntitySpawnBindingRepository; - Objects.requireNonNull(objectMapper, "objectMapper"); // Schema serialization must not inherit application-wide pretty-printing or map-order options. this.objectMapper = new ObjectMapper(); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java index c1767c1e1a..dfd32e16bb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -27,6 +27,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** * Internal-only World graph snapshot capture. Captured rows are representation evidence, not @@ -34,6 +35,7 @@ */ public class WorldAuthoredGraphSnapshotCapture { private static final int WORLD_DIGEST_SCHEMA_VERSION = 3; + private static final ObjectMapper STABLE_JSON = JsonMapper.builder().build(); private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); @@ -57,7 +59,6 @@ public class WorldAuthoredGraphSnapshotCapture { private final WorldAuthoredGraphReader graphReader; private final WorldDraftDesignDigestService draftDigestService; private final WorldAuthoredGraphSnapshotRepository snapshotRepository; - private final ObjectMapper objectMapper; @SuppressFBWarnings( value = "CT_CONSTRUCTOR_THROW", @@ -66,15 +67,13 @@ public class WorldAuthoredGraphSnapshotCapture { public WorldAuthoredGraphSnapshotCapture( DSLContext dsl, WorldDraftDesignDigestService draftDigestService, - WorldAuthoredGraphSnapshotRepository snapshotRepository, - ObjectMapper objectMapper) { + WorldAuthoredGraphSnapshotRepository snapshotRepository) { this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); this.graphReader = new WorldAuthoredGraphReader(dsl); this.draftDigestService = Objects.requireNonNull(draftDigestService, "draftDigestService must not be null"); this.snapshotRepository = Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); - this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } /** @@ -110,7 +109,7 @@ public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); WorldAuthoredGraph graph = graphReader.readAndValidateGraph(provenance.localTenantKey(), provenance.localVersionKey()); - byte[] graphBytes = graph.encode(objectMapper); + byte[] graphBytes = graph.encode(STABLE_JSON); WorldDraftDesignDigest currentDigest = draftDigestService.getDraftDesignDigest( Long.toString(provenance.localTenantKey()), @@ -205,7 +204,7 @@ private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvena return writeJson(evidence); } - private String encodeTuples(List tuples) { + static String encodeTuples(List tuples) { List> values = new ArrayList<>(); for (OwnedAffectedTuple tuple : tuples) { LinkedHashMap item = new LinkedHashMap<>(); @@ -249,17 +248,17 @@ private String captureRequestDigest( return sha256(writeJsonBytes(binding)); } - private String writeJson(Object value) { + private static String writeJson(Object value) { try { - return objectMapper.writeValueAsString(value); + return STABLE_JSON.writeValueAsString(value); } catch (Exception exception) { throw new SnapshotConflictException("World authored graph evidence could not be encoded"); } } - private byte[] writeJsonBytes(Object value) { + private static byte[] writeJsonBytes(Object value) { try { - return objectMapper.writeValueAsBytes(value); + return STABLE_JSON.writeValueAsBytes(value); } catch (Exception exception) { throw new SnapshotConflictException("World authored graph bytes could not be encoded"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java index 767a9c777e..4ba71e46e5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -30,7 +30,7 @@ /** Actual guarded six-family component storage; explicitly unwired, with private keys. */ public class WorldDraftTopologyCommitRepository { - private static final ObjectMapper OWNER_BINDING_JSON = JsonMapper.builder().build(); + private static final ObjectMapper STABLE_JSON = JsonMapper.builder().build(); private final DSLContext dsl; private final WorldDesignPublicationFenceRepository fence; @@ -56,8 +56,7 @@ public Optional readCommitted( } static String ownerBindingJson(WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { - return OWNER_BINDING_JSON.writeValueAsString( - Objects.requireNonNull(ownerBinding, "ownerBinding")); + return STABLE_JSON.writeValueAsString(Objects.requireNonNull(ownerBinding, "ownerBinding")); } /** Caller already holds the exact shared V25 FROZEN owner lock; no writer is entered. */ @@ -104,7 +103,7 @@ WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { "SELECT world_store_guarded_uuid_topology(?::jsonb, ?::jsonb, ?::jsonb)", ownerJson, plan.binding().canonicalJson(), - mapper.writeValueAsString(executionRevisions(plan))) + STABLE_JSON.writeValueAsString(executionRevisions(plan))) .fetch(); byte[] graph = readAndVerifyGraph(plan, owner.localTenantKey(), owner.localVersionKey()); byte[] result = encodeResult(plan, graph); @@ -401,7 +400,7 @@ private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant throw new ConflictException("World UUID association has no actual allocated row"); } JsonNode actual = mapper.readTree(row.get("content_json", String.class)); - JsonNode expected = mapper.valueToTree(expectedContent(node, keys, tenant, version)); + JsonNode expected = STABLE_JSON.valueToTree(expectedContent(node, keys, tenant, version)); if (!sameContent(actual, expected)) { throw new ConflictException("World allocated row differs from every exact payload field"); } @@ -471,7 +470,7 @@ private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant graph.put("canonicalTenantId", plan.graph().tenantId().toString()); graph.put("canonicalVersionId", plan.graph().versionId().toString()); graph.put("rows", rows); - return mapper.writeValueAsBytes(graph); + return STABLE_JSON.writeValueAsBytes(graph); } static Map expectedContent( @@ -600,7 +599,7 @@ private byte[] encodeResult(WorldDraftTopologyCommitPlan plan, byte[] graph) { return after; }) .toList()); - return mapper.writeValueAsBytes(result); + return STABLE_JSON.writeValueAsBytes(result); } private void requireTransaction() { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java index f67212d8ea..5230e989d5 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java @@ -652,6 +652,7 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() "filesystem:" + root.resolve("services/common-saga/src/main/resources/db/migration/saga")) .migrate(); + assertCanonicalFrozenMutationTriggerBindings(dsl, schema); var upstream = controlledSource(); var intake = Objects.requireNonNull( @@ -698,6 +699,14 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() .isEqualTo(WorldDraftTopologyCommitRepository.ownerBindingJson(plan.ownerBinding())) .isNotEqualTo(applicationMapper.writeValueAsString(plan.ownerBinding())); assertThat(topology.readCommitted(plan)).isPresent(); + var defaultMapperTopology = new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + var defaultMapperReadback = defaultMapperTopology.readCommitted(plan).orElseThrow(); + assertThat(defaultMapperReadback.graphBytes()).isEqualTo(stored.graphBytes()); + assertThat(defaultMapperReadback.resultBytes()).isEqualTo(stored.resultBytes()); + var defaultMapperReplay = + Objects.requireNonNull(write.execute(status -> defaultMapperTopology.store(plan))); + assertThat(defaultMapperReplay.graphBytes()).isEqualTo(stored.graphBytes()); + assertThat(defaultMapperReplay.resultBytes()).isEqualTo(stored.resultBytes()); // Exercise the snapshot reader against actual V1005 canonical spawn storage. This is // graph/codec proof only: it does not supply the missing V19 complete-commit history. var authored = @@ -813,8 +822,7 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() new RoomRepository(dsl), new RoomExitRepository(dsl), new GenerationRuleRepository(dsl), - new WorldEntitySpawnBindingRepository(dsl), - mapper); + new WorldEntitySpawnBindingRepository(dsl)); var actual = digest.getDraftDesignDigest( Long.toString(intake.localTenantKey()), Long.toString(version.localVersionKey())); @@ -884,11 +892,134 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() tuples); // Current capture must deny the actual synthetic checkpoint rather than invent APPLIED rows. var snapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); - var graphCapture = - new WorldAuthoredGraphSnapshotCapture(dsl, digest, snapshotRepository, mapper); + var graphCapture = new WorldAuthoredGraphSnapshotCapture(dsl, digest, snapshotRepository); assertThatThrownBy(() -> write.execute(status -> graphCapture.capture(capture))) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException.class) .hasMessageContaining("retained V19 revision history"); + + var originalRows = + dsl.fetchSingle( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json " + + "FROM world_authored_version_identity v " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id " + + "WHERE v.operation_id=?", + owner.versionIdentityOperationId()); + String identityJson = originalRows.get("identity_json", String.class); + String intakeJson = originalRows.get("intake_json", String.class); + + // These candidates reuse real stored topology/source bytes and must be rejected before + // persistence; none supplies or claims V19 complete-commit/APPLIED evidence. + var schemaTwoCapture = + new WorldAuthoredGraphSnapshot.CaptureRequest( + capture.targetNamespace(), + capture.canonicalTenantId(), + capture.canonicalVersionId(), + capture.intakeRequestId(), + capture.publicationFence(), + capture.publicationRequestId(), + capture.requestDigest(), + capture.versionStateEpoch(), + capture.publishWorkflowId(), + capture.appliedCommitId(), + capture.contentDigest(), + 2, + capture.suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(schemaTwoCapture), + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("New canonical graph capture requires digest schema 3") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + "{\"digestSchemaVersion\":3}", + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Canonical frozen capture differs") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + + var changedCheckpointCapture = + new WorldAuthoredGraphSnapshot.CaptureRequest( + capture.targetNamespace(), + capture.canonicalTenantId(), + capture.canonicalVersionId(), + capture.intakeRequestId(), + capture.publicationFence(), + capture.publicationRequestId(), + capture.requestDigest(), + capture.versionStateEpoch(), + capture.publishWorkflowId(), + capture.appliedCommitId() + "-mismatch", + capture.contentDigest(), + capture.digestSchemaVersion(), + capture.suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(changedCheckpointCapture), + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Canonical frozen capture differs") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_canonical_frozen_topology") + .get(0, Long.class)) + .isZero(); + + // Row-level V1006 UPDATE/DELETE guards cannot fire on an empty frozen table. Verify their + // installed shared-function bindings, and exercise UPDATE/DELETE on retained source rows. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_intake SET tenant_slug=tenant_slug " + + "WHERE operation_id=?", + intake.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("immutable") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("55000")); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id=?", + intake.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("immutable") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("55000")); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_authored_source_intake WHERE operation_id=?", + intake.operationId()) + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_canonical_frozen_topology")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("immutable") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("55000")); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_canonical_frozen_topology") + .get(0, Long.class)) + .isZero(); + assertThat( dsl.fetchSingle("SELECT count(*) FROM world_authored_graph_snapshot") .get(0, Long.class)) @@ -910,6 +1041,96 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() } } + private static void assertCanonicalFrozenMutationTriggerBindings(DSLContext dsl, String schema) { + var triggers = + dsl.fetch( + "SELECT t.tgname AS trigger_name, p.proname AS function_name, " + + "pg_get_triggerdef(t.oid) AS trigger_definition, p.prosrc AS function_source " + + "FROM pg_trigger t " + + "JOIN pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_namespace n ON n.oid=c.relnamespace " + + "JOIN pg_proc p ON p.oid=t.tgfoid " + + "WHERE n.nspname=? AND c.relname='world_canonical_frozen_topology' " + + "AND NOT t.tgisinternal ORDER BY t.tgname", + schema); + assertThat(triggers.getValues("trigger_name", String.class)) + .containsExactly( + "trg_world_canonical_frozen_00_schema3", + "trg_world_canonical_frozen_immutable", + "trg_world_canonical_frozen_insert", + "trg_world_canonical_frozen_no_truncate"); + assertThat(triggers.getValues("function_name", String.class)) + .containsExactly( + "world_require_new_digest_schema3_capture", + "world_reject_authored_source_history_mutation", + "world_check_canonical_frozen_capture", + "world_reject_authored_source_history_mutation"); + assertThat(triggers.get(1).get("trigger_definition", String.class)) + .contains( + "DELETE", "UPDATE", "FOR EACH ROW", "world_reject_authored_source_history_mutation"); + assertThat(triggers.get(3).get("trigger_definition", String.class)) + .contains( + "TRUNCATE", "FOR EACH STATEMENT", "world_reject_authored_source_history_mutation"); + assertThat(triggers.get(1).get("function_source", String.class)) + .contains("RAISE EXCEPTION", "ERRCODE = '55000'") + .doesNotContain("IF "); + var sourceFunctions = + dsl.fetch( + "SELECT p.proname AS function_name FROM pg_trigger t " + + "JOIN pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_namespace n ON n.oid=c.relnamespace " + + "JOIN pg_proc p ON p.oid=t.tgfoid " + + "WHERE n.nspname=? AND c.relname='world_authored_source_intake' " + + "AND NOT t.tgisinternal ORDER BY t.tgname", + schema) + .getValues("function_name", String.class); + assertThat(sourceFunctions) + .containsExactly( + "world_reject_authored_source_history_mutation", + "world_reject_authored_source_history_mutation"); + } + + private static void insertCanonicalFrozenCandidate( + DSLContext dsl, + WorldDraftTopologyCommitPlan plan, + WorldAuthoredGraphSnapshot.CaptureRequest request, + WorldDraftTopologyCommitEvidence stored, + String freezeRequestJson, + String identityJson, + String intakeJson) { + dsl.execute( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence," + + "request_id,commit_id,version_identity_operation_id,freeze_request_json," + + "owner_binding_json,binding_json,binding_digest,identity_json,intake_json," + + "graph_bytes,graph_sha256,storage_result_bytes,result_bytes,capture_status) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + UUID.randomUUID(), + request.publicationFence(), + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + freezeRequestJson, + WorldDraftTopologyCommitRepository.ownerBindingJson(plan.ownerBinding()), + plan.binding().canonicalJson(), + plan.binding().digest(), + identityJson, + intakeJson, + stored.graphBytes(), + WorldAuthoredGraphSnapshotCapture.sha256(stored.graphBytes()), + stored.resultBytes(), + stored.resultBytes(), + WorldCanonicalFrozenTopology.STATUS); + } + + private static String sqlState(Throwable throwable) { + for (Throwable cause = throwable; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } + private static WorldDraftTopologyCommitPlan topologyPlan( WorldAuthoredSourceIntakeReceipt intake, WorldAuthoredVersionIdentityReceipt version) throws Exception { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java index c3539252bf..974f04dd5f 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java @@ -12,7 +12,6 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import tools.jackson.databind.ObjectMapper; class WorldDraftDesignDigestServiceImplTest { @Test @@ -32,8 +31,7 @@ void rejectsZeroTenantIdBeforeRepositoryReads() { roomRepository, roomExitRepository, generationRuleRepository, - worldEntitySpawnBindingRepository, - new ObjectMapper()); + worldEntitySpawnBindingRepository); assertThrows(IllegalArgumentException.class, () -> service.getDraftDesignDigest("0", "7")); @@ -63,8 +61,7 @@ void rejectsZeroVersionIdBeforeRepositoryReads() { roomRepository, roomExitRepository, generationRuleRepository, - worldEntitySpawnBindingRepository, - new ObjectMapper()); + worldEntitySpawnBindingRepository); assertThrows(IllegalArgumentException.class, () -> service.getDraftDesignDigest("1", "0")); @@ -106,8 +103,7 @@ void computesDigestFromVersionScopedTemplateRows() { roomRepository, roomExitRepository, generationRuleRepository, - worldEntitySpawnBindingRepository, - new ObjectMapper()); + worldEntitySpawnBindingRepository); var digest = service.getDraftDesignDigest("1", "7"); @@ -128,8 +124,7 @@ void canonicalSpawnReferenceAffectsSchemaThreeDigestAndMixedReferencesDeny() { var rules = Mockito.mock(GenerationRuleRepository.class); var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); var service = - new WorldDraftDesignDigestServiceImpl( - regions, zones, rooms, exits, rules, spawns, new ObjectMapper()); + new WorldDraftDesignDigestServiceImpl(regions, zones, rooms, exits, rules, spawns); var room = new net.firedevops.firemud.worldmanagement.entity.Room(); room.setId(11L); var spawn = new net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCaptureSerializationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCaptureSerializationTest.java new file mode 100644 index 0000000000..9976bef807 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCaptureSerializationTest.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class WorldAuthoredGraphSnapshotCaptureSerializationTest { + @Test + void ownedAffectedTuplesKeepStableDefaultJsonBytes() { + var tuple = + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + "WORLD_MANAGEMENT", "REGION", "region-1", "", "", "7"); + + assertThat(WorldAuthoredGraphSnapshotCapture.encodeTuples(List.of(tuple))) + .isEqualTo( + "[{\"owner\":\"WORLD_MANAGEMENT\",\"aggregateType\":\"REGION\"," + + "\"aggregateId\":\"region-1\",\"scopeType\":\"\"," + + "\"scopeId\":\"\",\"expectedEpoch\":\"7\"}]"); + } +} From 33860ed67bda8c4cefd8c22fd9afe2199351f384 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:05:11 +1300 Subject: [PATCH 5/7] Align World component proof status and remaining capture limits --- .../microservices/world-management-service/api-contracts.md | 2 +- .../microservices/world-management-service/runtime-and-data.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 27644453f1..4e8be0f5dd 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The source-retention cut itself does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. A separate component-owner candidate includes graph capture and the ordinary schema-3 digest writer; its checkpoint producer and focused proof remain incomplete, as recorded in the tracker. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The source-retention cut itself does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. A separate component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture remain unqualified. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 6bab85e238..46db62ee0b 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its source-retention migrations are `V23.1` and `V24`–`V27.2`; the guarded component-owner stage adds `V1003`–`V1007.1`. These forward-only migrations preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The guarded component-owner candidate includes graph capture and the ordinary schema-3 digest writer; its exact checkpoint producer remains unqualified, and focused component proof is recorded in the tracker. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its source-retention migrations are `V23.1` and `V24`–`V27.2`; the guarded component-owner stage adds `V1003`–`V1007.1`. These forward-only migrations preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The guarded component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture remain unqualified. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. From f4e63c0a71567f9b800111135e712258ed0feb75 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:30:28 +1300 Subject: [PATCH 6/7] Align Game Design tracker with required World schema three --- .../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 1cca61a82e..b908b5fceb 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 @@ -111,7 +111,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` 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-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 3, and the full-Version gate requires schema 3. 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. | @@ -186,7 +186,7 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: durable `version_asset` mappings and a version-scoped export snapshot have independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published exact-byte repair independently reads the candidate and checks it against the exact release bundle before object writes; repair does not create a snapshot or candidate. Candidate origin and snapshot-integrity checks are present, while integrated migration closure and focused physical database/object-store execution remain unproved. Destructive lifecycle operation safety, global publication/purge fencing, restart recovery, and runtime readiness remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions). -Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. Public and registered Temporal ingress deny fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association. FAILED replay returns the stored result; SUCCEEDED replay requires exact immutable release readback. Source capture, candidate export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The candidate path retains its frozen origin and snapshot integrity, and the finalizer requires a captured operation and same-transaction terminal seal. The local owner-proof boundary rejects `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` before Version mutation; neither establishes Account authority or lifecycle-transition safety. Physical database, object-store, rollback, concurrent retry, committed/absent/ambiguous recovery, and live Temporal-owner execution remain unproved. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. Full-version publication also lacks Game Logic owner-local manifest/provenance for version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest, candidate, and asset lifecycle contracts are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The current release storage preserves canonical Version identity, an opaque reference, manifest schema, artifact digests, and exact persisted bundle readback; canonical target-commit provenance and a public tenant projection remain absent. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md). +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. Public and registered Temporal ingress deny fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association. FAILED replay returns the stored result; SUCCEEDED replay requires exact immutable release readback. Source capture, candidate export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The candidate path retains its frozen origin and snapshot integrity, and the finalizer requires a captured operation and same-transaction terminal seal. The local owner-proof boundary rejects `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` before Version mutation; neither establishes Account authority or lifecycle-transition safety. Physical database, object-store, rollback, concurrent retry, committed/absent/ambiguous recovery, and live Temporal-owner execution remain unproved. World emits schema `3`, and the full-Version gate requires schema `3`; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. Full-version publication also lacks Game Logic owner-local manifest/provenance for version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest, candidate, and asset lifecycle contracts are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The current release storage preserves canonical Version identity, an opaque reference, manifest schema, artifact digests, and exact persisted bundle readback; canonical target-commit provenance and a public tenant projection remain absent. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md). Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. From 122d6a887ca3bac317a5f8c7e12cba35dbf110a4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:52:42 +1300 Subject: [PATCH 7/7] Allow Game Session proof jobs thirty minutes --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c44d05133..52ac10286b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -990,8 +990,8 @@ jobs: permissions: contents: read id-token: write - # Account and World PostgreSQL proofs can run close to 20 minutes before Gradle post-job cleanup. - timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'world-management-service') && 30 || 20 }} + # Account, World and Game Session proofs can run close to 20 minutes before Gradle post-job cleanup. + timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'world-management-service' || matrix.module == 'game-session-service') && 30 || 20 }} strategy: fail-fast: false matrix: