From 400adc558f3264dddb09601db424cd9b0bffe689 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:17:49 +1300 Subject: [PATCH 01/11] Contain unqualified script publication and surface readiness rejection Receive compatible #2856 publication/readiness/launch source while preserving current UUID, full-publication refusal and original DRAFT/PENDING retention. Do not import obsolete synchronous fallback or absence cleanup. Exact manifest/readiness producers and durable zero-handler failure/status/audit convergence remain held. --- ...ess-without-durable-game-initialization.md | 2 +- .../api-contracts.md | 12 +- .../runtime-and-data.md | 4 +- .../game-design-service/README.md | 6 +- .../game-design-service/api-contracts.md | 2 +- .../game-design-service/version-control.md | 4 +- ...e-scripting-dsl-reference-and-lifecycle.md | 6 +- .../system-architecture-scripting.md | 6 +- .../system-architecture-temporal-workflows.md | 2 +- design/project-management/ai-observations.md | 2 +- .../automation-and-scheduler-runtime.md | 6 +- ...ame-authoring-publishing-and-activation.md | 14 +- protos/automation-scripting/v1/README.md | 4 +- .../service/ScriptVersionService.java | 2 +- .../impl/AutomationScriptingGrpcService.java | 68 +-- .../impl/ScriptVersionServiceImpl.java | 3 +- .../AutomationScriptingGrpcServiceTest.java | 155 ++--- .../impl/NpcFormationGrpcServiceTest.java | 2 - .../ScriptPatchVersionCommandServiceTest.java | 2 +- .../impl/ScriptVersionServiceImplTest.java | 24 +- .../client/AutomationScriptingClient.java | 40 +- .../impl/LaunchDescriptorServiceImpl.java | 5 + .../service/impl/VersionServiceImpl.java | 187 +++--- ...emptServiceTransactionIntegrationTest.java | 317 ++++++++-- .../client/AutomationScriptingClientTest.java | 78 ++- .../impl/GameDesignGrpcServiceTest.java | 29 + .../impl/LaunchDescriptorServiceImplTest.java | 47 ++ .../service/impl/VersionServiceImplTest.java | 575 +++++++++++++----- 28 files changed, 1107 insertions(+), 497 deletions(-) diff --git a/design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md b/design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md index 77a8156594..6721fe0acb 100644 --- a/design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md +++ b/design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The current path admits bounded tenant-readiness `onLoad` work and exposes a readiness projection, but it does not yet seal or prove the immutable complete handler manifest required by this ADR. Game Design currently notifies Automation with an empty `affectedScripts` list; Automation returns before creating readiness state, and its Temporal tracking hook also skips empty lists. Normal script-patch publication therefore does not currently establish a readiness candidate or workflow. For non-empty notifications, Automation resolves only definitions found by name and seeds readiness from that found set; an incomplete expected-handler comparison can therefore mark a patch `READY` while required definitions are missing. Notification transport and response failures are swallowed without a durable redrive, so publication can remain `PUBLISHED` without a readiness candidate or workflow. An explicit empty handler set is valid only when the immutable patch manifest proves that zero handlers are required. For an identifiable tenant/patch notification, absent or unverifiable zero-handler proof has one canonical outcome: the readiness owner durably records `FAILED` with a bounded reason such as `zero_handler_manifest_unverifiable`, publishes the normal readiness status/audit evidence, and does not silently reject, bypass `onLoad`, start synthetic handler work, or retry the DSL. An unidentifiable malformed notification may still fail at transport/validation without fabricating a patch identity. Monotonic publication acceptance and late-completion fencing, along with readiness-owner recovery and terminalization of stale `ONLOAD_RUNNING` work, remain target convergence and proof gaps; the generic replay behavior described in the automation tracker is implementation drift rather than supported readiness recovery. +The immutable complete handler-manifest and readiness-owner convergence remain incomplete. Current containment reports unsuccessful readiness instead of silent notification success, and Game Design refuses new patch publication without verified manifest evidence while retaining uncertain originals. The identifiable zero-handler path still lacks the durable `FAILED` projection and normal status/audit evidence required by this decision; no successful readiness or activation claim follows from rejection alone. Current scope, proof and remaining owner work belong to the [Automation tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md) and [Game Design tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). ## Decision Record diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 5a8bf331e5..956486ca9b 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -25,11 +25,11 @@ Target formation control-plane behavior eliminates unauthenticated service-local - `GetScriptBreakerStatus` and `ListScriptBreakerEvents` are target-state reads for the exact `(tenantId, gameInstanceId, scriptPatchVersion, scriptPinEpoch, scriptId)` core-script breaker identity, and `ResetScriptBreaker` is its target operator mutation. The current proto/implementation has no authoritative breaker status/history surface, monotonic breaker revision, reset mutation, stored request result, or reset evidence. They are distinct from `GetScriptPatchStatus` tenant readiness and `GetScriptStatus` pre-DSL work states; do not introduce or infer a `scriptVersionId`. - Target pre-DSL recovery permits rebuilding `PENDING_EVALUATION` and only an `EVALUATING` row whose owner proves the lease stale or explicitly releases ownership through one fenced compare-and-set covering the status, owner, freshness, and fence transition; unresolved, ambiguous, and non-stale rows remain excluded. The callable `rebuildPendingWorkItemIndex` remains an unsafe helper with no stale, owner, or compare-and-set reconciliation gate, so current queue reset/resume is unavailable and must fail closed; no live scheduled rebuild invokes it, and a non-atomic status preflight cannot authorize recovery. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). It does not implement target `PENDING`/`INDEXED` evaluated-descriptor rebuild because the separate descriptor status layer is not currently persisted; these pointers are not evaluated-command queue entries or descriptor replay evidence. - For a non-empty `NotifyScriptVersionUpdate` notification, the current path validates and stages patches through `PENDING_VALIDATION -> ONLOAD_RUNNING -> READY/FAILED/SUPERSEDED`; running instances reload only after a later pin change to that tenant-`READY` patch. -- In the current normal Game Design integration, `affectedScripts` is empty. Automation returns before creating readiness state, and the conditional Temporal start is skipped, so publication does not establish a readiness row or workflow; this is a current implementation gap, not readiness proof. An empty list is valid only when an immutable patch manifest proves that zero `onLoad` handlers are expected. For an identifiable tenant/patch notification without that proof, the canonical target outcome is a durable `FAILED` readiness record with bounded reason `zero_handler_manifest_unverifiable`, normal status/audit evidence, no synthetic handler work, and no DSL retry; it may not advance the patch to `READY`. An unidentifiable malformed notification may fail at transport/validation without fabricating a patch identity. The lifecycle above is therefore target/non-empty behavior, not an outcome guaranteed after every notification. +- In the current normal Game Design integration, `affectedScripts` is empty. Automation now returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and does not create readiness state or synthetic handler work. This is fail-closed containment, not the accepted terminal outcome: for an identifiable tenant/patch without verifiable zero-handler proof, ADR 0115 requires one durable `FAILED` readiness record with normal status/audit evidence and no DSL retry. That durable failure is not implemented in the current readiness owner, so the empty notification remains a readiness and publication blocker. An unidentifiable malformed notification may fail at transport/validation without fabricating a patch identity. For non-empty notifications, the readiness boolean is propagated to the RPC response; `success=true` means the owner accepted the current readiness operation, not that all handlers reached `READY`. - The current `ListScriptHandoffEvents` proto/client reads handoff rows using `workItemId`/persisted `outboxWorkItemId`, `gameSessionCommandId`, `automationDispatchId`, and the currently supported scope, remote, provenance, routing, target, and source fields. The target complete Command-Handoff Identity and complete evaluated-descriptor semantics remain target-only end-to-end; locally stored ordinal/text/target values do not establish that target contract. The current proto/client exposes no `bindingId` request filter, and target response metadata remains target-state follow-through rather than a claimed live field. - `GetAutomationPinConvergence` is currently served from a durable Automation-owned `script_patch_pin_projections` view keyed by `(tenantId, gameInstanceId)` and returns freshness flags (`projectionAsOfMs`, `projectionLagMs`, `isProjectionStale`) so temporary Game Session read failures do not collapse operator visibility into raw pass-through coupling. - Signer/component-policy enforcement is live on the Automation runtime side. The current control-plane surface exposes `GetPluginStatus`, `ListPluginRuntimeEvents`, and `GetPluginPolicyConvergence`, and scheduled reconciliation disables enabled plugins when current publication metadata becomes fail-closed. The separate propagation-event families `SignerPolicyVersionObserved` and `SignerRevocationApplied` remain target-state follow-through rather than a shipped API family. -- Script-patch digesting already attests the patch-scoped script graph for `scriptPatchVersion`. The current full-version digest attests the tenant's draft script graph using the existing schema and returns synthetic `appliedCommitId = "version:"` until script definitions are modeled as fully version-scoped draft data. +- The registered `GetDraftDesignDigest` receiver currently returns `UNSUPPORTED_SCOPE` for both full-version and script-patch selectors after authenticating and validating the exact request binding. Existing helper digests do not prove exact version-scoped full content or an owner-verified base-bound patch manifest, so their synthetic or incomplete results are not exposed as publication attestations. The separate selected-empty full-version reader below remains unregistered and does not change this denial. - The current executor supports bounded multiple emitted commands with local ordinals and per-command handoff attempts; the complete Command-Handoff Identity and end-to-end per-command progress remain target-only. See [Scripting & Automation: Cross-Service Contracts](../../system-architecture-scripting-contracts.md#implementation-status) for the owner contract and current wire consequence. `command_count_exceeded` applies only to an actual configured output-count limit. - The current ingress/remote payload may carry `readSnapshotToken`, but Automation does not yet persist the complete handler-scoped input manifest with owner versions, artifacts, causal floor, and seed version; manifest sealing and descriptor replay remain target-state gaps. - Durable parent-event identity, canonical request-digest conflict handling, an atomically frozen ordered handler manifest, binding-scoped plugin execution identity, and activation-epoch fencing under ADR 0172 are not implemented. Current retries can still re-resolve mutable handler state. @@ -63,9 +63,9 @@ curl http://localhost:8080/ping - `UpdateScript` – bootstrap/dev-only script upload path that replaces the script definition and its event bindings for the `(tenantId, version, name)` tuple in one operation. This is the stable definition identity enforced by the `scripts` table; it is distinct from runtime patch/script identity `(tenantId, scriptPatchVersion, scriptId)`. The definition write uses one PostgreSQL upsert, so an exact retry reuses the same retained row/ID and concurrent retries cannot insert duplicates; changed input on an existing tuple replaces the definition and bindings atomically rather than creating a second definition or a request-ID conflict. v1 has no separate request ID for this path; the current response reports success, not the row ID. - `GetScriptStatus` – queries durable queued work (`PENDING_EVALUATION`) and active evaluation work (`EVALUATING`) in the script work-item outbox. - `GetScriptBreakerStatus` – **target-state read:** returns the exact core-script breaker tuple, `breakerState`, bounded `breakerReason`, monotonic `breakerRevision`, monotonic `breakerSampleGeneration`, policy/window/classified-sample evidence, audited reset evidence when applicable, and timestamps. `ListScriptBreakerEvents` is the corresponding bounded history read with optional tuple/state/time selectors and explicit `TRIPPED`/`RESET` transitions. `ResetScriptBreaker` is the target operator mutation: it selects the same exact tuple, requires expected disabled state/revision plus bounded validation evidence, and atomically resets through the revision-fenced owner history contract while advancing the sample generation so pre-reset samples remain history-only. The current proto/implementation exposes none of these surfaces; canonical field, authorization, idempotency, concurrency, and reset semantics live in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md#getscriptbreakerstatus). -- `NotifyScriptVersionUpdate` – production rollout notification to Automation & Scripting that a Game Design-published `script_patch_version` is available for tenant-readiness ingestion. +- `NotifyScriptVersionUpdate` – production rollout notification to Automation & Scripting that a Game Design-published `script_patch_version` is available for tenant-readiness ingestion. The current empty-list path returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and creates no readiness row; ADR 0115's required durable `FAILED` record with status/audit evidence remains unimplemented. - Event-ingress RPCs such as `TriggerScriptEvent` or a batch equivalent deliver script events from domain services and must carry runtime scope, idempotency, and patch-selection fields as described below. -- `GetDraftDesignDigest` – returns publish-gating digest for full publishes and script-patch publishes using a typed scope selector `oneof { versionId, scriptPatchVersion }`. +- `GetDraftDesignDigest` – accepts a typed scope selector `oneof { versionId, scriptPatchVersion }`; the current registered receiver returns `UNSUPPORTED_SCOPE` for both scopes rather than exposing helper results that lack exact publication mapping. ```bash grpcurl -plaintext localhost:6565 automation_scripting.v1.AutomationScriptingService/Ping @@ -274,7 +274,7 @@ This service is a required digest participant for full publishes and script-patc Publish gating must fail closed when the service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. -**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Automation's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered full-version reader remains unchanged; this primitive does not make Automation publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with all three declared script, event-binding, and patch-base-binding families explicitly empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. This selected-empty full-version semantic path uses `digestSchemaVersion=6`; the existing script-patch digest remains schema 5 with its existing behavior. +**Current selected-empty status:** An unregistered owner-local reader provides a bounded selected-empty full-version primitive over Automation's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. It remains unregistered and does not change the registered `GetDraftDesignDigest` receiver, which currently returns `UNSUPPORTED_SCOPE` for both scope types. It therefore does not make Automation publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with all three declared script, event-binding, and patch-base-binding families explicitly empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. This selected-empty full-version semantic path uses `digestSchemaVersion=6`; it does not establish the registered script-patch digest, which remains unavailable pending exact mapping. The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Automation numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. Its SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `automation-selected-empty-publication-digest/v1`, schema `6`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Automation inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. This subset is not a claim that nonempty full-version script graphs or bindings are covered, and schema-6 participant evidence is not created by rewriting old evidence. @@ -284,6 +284,6 @@ The selected-empty service also requires the complete incoming publication reque For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission. -**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The existing script-patch content digest remains schema 5 and includes the retained base version; the selected-empty schema-6 primitive is unregistered and does not replace the live full-version reader, whose input remains tenant-wide. Multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. +**Current status:** `GetDraftDesignDigest` invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before returning `UNSUPPORTED_SCOPE` for either selector. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The selected-empty schema-6 primitive remains unregistered; exact version mapping and the base-bound patch manifest are still required before a publication digest can be returned. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The guard requires the exact authenticated Game Design workload mTLS peer and denies account or role-bearing context; role-free internal identity alone is not authorization or a substitute for that peer. Live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its existing live full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 24b45510ab..641d782a86 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -21,7 +21,7 @@ The plugin lifecycle histories are separate ADR 0163 retained families. `plugin_ The current admission barrier supports the optional regional selector and now implements the durable acknowledgement slice: boundary normalization preserves exact scope/mode/request identity, a length-delimited SHA-256 fingerprint binds the request, and immutable `APPLIED`/`ALREADY_APPLIED` history supports exact retry readback and changed-input conflict. The operator Get path performs a read-only exact-scope lookup, returns `NOT_FOUND` for an absent state and `ACKNOWLEDGEMENT_UNAVAILABLE` when durable successful history is missing, and never reconstructs missing history from mutable state. Response fields expose the successful acknowledgement identity, target mode, fingerprint, outcome, and timestamp. Direct V1 schema and focused unit proof cover this slice. Exact-head hosted CI, Automation service checks, and generic full-stack smoke passed. Hosted `integrationTest` executed against Docker/PostgreSQL and passed, but the hosted logs/artifact do not expose a trustworthy exact test count; the local exact-head integration run discovered 33 tests and skipped all 33 because Docker/Testcontainers was unavailable. Generic full-stack smoke did not exercise admission behavior and is not claimed as admission proof. The separate preview endpoint was unavailable at capacity. The target owner contract is [SetAutomationAdmissionMode](../../system-architecture-scripting-control-plane-api.md#setautomationadmissionmode); the [local API contract](./api-contracts.md#script-patch-and-plugin-visibility-apis) records this service's consequence. Immutable admission request history currently has no cleanup and remains retained; safe pruning and production launch require a future ADR 0163/ADR 0123 owner, horizon, and tombstone design, so this boundary adds no arbitrary TTL. -Tenant-readiness mutation now serializes per tenant, preserves admitted identities on retry, and fails duplicate or unresolved script names before admission. The V2 unique active-tenant index fails closed on retained duplicates. PostgreSQL proof and the remaining manifest, notification, generation-fence, and recovery gaps are recorded in the [Automation implementation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#current-status); this bounded correction is not complete publication readiness. +Tenant-readiness mutation now serializes per tenant, preserves admitted identities on retry, and fails duplicate or unresolved script names before admission. The V2 unique active-tenant index fails closed on retained duplicates. The RPC reports the readiness owner's boolean result rather than unconditional success. An empty `affectedScripts` notification returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and admits no synthetic work, but it still creates no readiness row. ADR 0115 requires a durable `FAILED` status with normal audit evidence for an identifiable patch without verified zero-handler proof; the current projection owner does not yet provide that terminal-write operation. PostgreSQL proof and the remaining manifest, notification, generation-fence, and recovery gaps are recorded in the [Automation implementation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#current-status); this bounded correction is not complete publication readiness. The same V2 migration replaces handler work-item and audit identities so authenticated `sourceService` participates in both pinned and unpinned uniqueness. Ingress now supplies that owner-derived value to repository duplicate checks, conflict targets, and exact readback, so equal producer-local event identities from different services remain independent while an exact same-source retry deduplicates. Migration-shape and focused repository tests execute locally; the PostgreSQL same-source/different-source integration case compiles but was skipped because Docker was unavailable. This does not close the separate namespace, sealed-manifest, lifecycle-fence, replay, or retention gaps. @@ -78,7 +78,7 @@ Publication consumes this empty-only receipt only within the [canonical selected - AI computations are optimized for large worlds by evaluating scripts on a separate schedule and batching the resulting commands before handing them to the tick system. - Script definitions are versioned and can be hot reloaded without downtime as described in [System Architecture: Scripting & Automation](../../system-architecture-scripting.md). Detailed sandbox and loop-safety rules live in [Script Sandbox & Resource Limits](./sandbox-runtime-design.md). - For a non-empty `NotifyScriptVersionUpdate` notification, the service reloads the specified patch into tenant-readiness state, validating compatibility and running `onLoad` before any running instance is allowed to switch to it. Tenant readiness is single-pending per tenant: if a newer publish arrives before the current pending patch reaches a terminal state, the older pending patch becomes `SUPERSEDED` and cannot later advance to `READY`. -- In the current normal Game Design integration, `affectedScripts` is empty, so the notification handler returns before creating readiness state and no readiness row or Temporal workflow is created. An empty list is valid only when an immutable patch manifest proves that zero `onLoad` handlers are expected; for an identifiable tenant/patch notification without that proof, the readiness owner must durably record `FAILED` with bounded reason `zero_handler_manifest_unverifiable` and normal status/audit evidence, and may not advance the patch to `READY` or bypass the mandatory `onLoad` gate. An unidentifiable malformed notification may fail at transport/validation without fabricating a readiness identity. The lifecycle above describes target/non-empty behavior rather than every notification. +- In the current normal Game Design integration, `affectedScripts` is empty. The receiver returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; no readiness row or synthetic handler work is created, and Temporal tracking is not started. This is fail-closed containment, not the accepted terminal outcome: for an identifiable tenant/patch without verifiable zero-handler proof, ADR 0115 requires one durable `FAILED` readiness record with normal status/audit evidence. The current readiness owner lacks an operation for that terminal write, so the required record remains a publication blocker. An unidentifiable malformed notification may fail validation without fabricating a readiness identity. - **Target state:** Runtime execution is instance-aware even when patch readiness is tenant-scoped: a tenant-level `READY` patch is only eligible for pinning, while admission, timer scheduling, and scoped Automation admission pause are evaluated per ``, and plugin activation is evaluated per ``. Plugin-backed work captures the Automation-owned `pluginActivationEpoch` and owner `lifecycleRevision` and preserves and revalidates both through evaluation, persistence, handoff, staged/final effects, retry, replay, and recovery. Game Session remains the sole authority for the exact `(scriptPatchVersion, scriptPinEpoch)` execution tuple and its owner-grounded `controlPlaneRequestId` evidence; runtime surfaces carry and compare the request ID with the patch and epoch, and absent or mismatched evidence fails closed. The request ID is correlation/readback evidence, not a third pin-identity component. - Automation is also a lifecycle owner for these instance-scoped work, schedule, and plugin-runtime families: each family must be registered with World Management's durable cleanup-owner inventory, expose idempotent cleanup and acknowledgement, and retain namespace-backed durable state according to its S1/S2/S3 classification. A missing owner registration or cleanup acknowledgement blocks termination; local queue/drain state and workflow history are diagnostic only. - **Current cleanup behavior:** The scheduled `ScriptWorkItemServiceImpl.cleanupTerminalWorkItems` path selects eligible `HANDED_OFF` and `CANCELED` `script_work_items` rows under lock, applies each status-specific parent age cutoff, and requires every associated handoff event to have a completed outcome, no active hold, and an `observed_at` before that same cutoff. Within the caller transaction, it detaches nullable `script_event_audit.work_item_id` links, deletes eligible `script_handoff_events` children, and then deletes the parent rows. A newer child retains the parent bundle until its own age condition is met. Any retained `script_dead_letter_replay_results` row blocks parent deletion regardless of age; retained audit rows remain under their independent retention policy. Separately, `ScriptHandoffEventRepository.deleteExpiredRetentionEvidence` exposes a child-only sweep in ordered batches of at most 500. It deletes only completed, expired, unheld handoffs when every sibling is also eligible, no replay receipt is retained, and the existing parent is terminal but not `DEAD_LETTERED`; orphaned children with a missing parent are not eligible. It does not require the existing parent to pass a status-specific age cutoff. This repository method has no current scheduled caller. Automatic age- and row-cap cleanup of `DEAD_LETTERED` parents fails closed and deletes nothing: the live schema has a per-work-item `failure_generation` and generation-bound replay-result receipts, but it does not yet retain the recovery aggregate's generation-bound claim/attempt state, expected-child ledger, or evidence-retention horizons needed to prove whole-bundle eligibility and completed `resumed_dispatch`. Focused unit proof covers fail-closed parent cleanup and the bounded handoff query; PostgreSQL retention cases require Docker/Testcontainers at execution time. Target cleanup must retain or explicitly dispose each child handoff/audit record under its owning retention, safety-evidence, replay, and lifecycle contracts, and only delete a parent when those child dispositions and required audit evidence are durably settled. The target retention rules remain owned by the scripting normative contracts and applicable lifecycle/operations documents. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index ca02a38ca7..4b839ad5c4 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -53,16 +53,16 @@ The canonical authored-world launch slice includes source-qualified ResolveLaunc ### Script Patch Lifecycle and Runtime Coordination -The Game Design Service owns the **authoring** view of script patches, while the Automation & Scripting Service owns the **runtime** lifecycle of those patches per tenant. The detailed validation, schedule-identity compilation, and ability-schema-digest steps below are target state; the current `PublishScriptPatchVersion` path creates the patch version, runs the available participant digest gates, notifies Automation, and publishes without proving those script-graph, schedule, or immutable ability-schema computations. The current notification sends an empty `affectedScripts` list; Automation returns before creating readiness state or starting Temporal tracking for that input, so ordinary patch publication does not currently establish a readiness candidate. +The Game Design Service owns the **authoring** view of script patches, while Automation & Scripting owns tenant readiness. Publication and launch consume owner-verified manifest and exact base/readiness evidence under [Version Control](version-control.md#script-patch-versions-and-runtime-behavior). The current containment refuses new patch publication before notification when the handler manifest is unavailable, preserves retained attempts and tuple custody, and refuses patched launch descriptors without canonical owner evidence. Source and unrun proof limits belong to [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). - When `PublishScriptPatchVersion` is called, the Game Design Service: - **Target state:** Validates and persists the new script graphs, bindings, and metadata, including cross-asset compatibility checks against the pinned `baseVersionId` (for example, ensuring referenced ability identifiers exist and match the ability schema for that base version). - **Target state:** Compiles stable runtime identities needed for reconciliation, including a `scheduleDefinitionId` for each logical timer/interval definition so Automation & Scripting can preserve or tombstone schedules deterministically across patch changes. - **Target state:** Computes or reads an immutable `abilitySchemaDigest` for the pinned `baseVersionId` and records it with the patch metadata used for runtime validation. - - **Target state:** Notifies Automation & Scripting of the published patch so it can ingest the compiled definitions and bindings for the target `` and, for an eligible non-empty handler notification, start or reuse the durable Temporal `script-patch-readiness` workflow. Target state permits a verifiable immutable manifest with zero `onLoad` handlers to instead create the terminal `READY` pin-readiness record with its pinned manifest reference/digest and zero declared and terminal handler counts, without a Temporal workflow or synthetic handler work. The current publication notification sends only `affectedScripts`, and current status responses have no manifest-proof or declared/terminal-count fields, so the current wire/runtime cannot supply or expose this proof; an empty current notification does not create readiness. + - **Target state:** Notifies Automation & Scripting of the published patch so it can ingest the compiled definitions and bindings for the target `` and, for an eligible non-empty handler notification, start or reuse the durable Temporal `script-patch-readiness` workflow. Target state permits a verifiable immutable manifest with zero `onLoad` handlers to instead create the terminal `READY` pin-readiness record with its pinned manifest reference/digest and zero declared and terminal handler counts, without a Temporal workflow or synthetic handler work. The current wire/status shape cannot supply complete manifest proof; Game Design therefore refuses new patch publication before notification. Identifiable empty-handler notifications reaching Automation remain governed by ADR 0115's durable readiness-owner failure rule. - Treats the publish as **asynchronous** from a runtime perspective: the version is recorded as published in design-time tables, but its readiness for execution is determined by the Automation & Scripting Service. - **Target state:** For each `` with an eligible `NotifyScriptVersionUpdate` notification, including a valid affected-script set (or a manifest-proven zero-handler set), the Automation & Scripting Service tracks a tenant readiness lifecycle (`PENDING_VALIDATION`, `ONLOAD_RUNNING`, `READY`, `FAILED`, and terminal `SUPERSEDED`) as described in `design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md#script-patch-lifecycle`. An empty `affectedScripts` list without immutable manifest proof cannot establish `READY`: for an identifiable tenant/patch notification, Automation records durable `FAILED` readiness with bounded reason `zero_handler_manifest_unverifiable` and status/audit evidence; an unidentifiable malformed notification may fail transport validation without fabricating a readiness identity. `SUPERSEDED` applies only to a displaced, unpinned record in `PENDING_VALIDATION` or `ONLOAD_RUNNING`; an already-pinned `READY` record is not relabeled `SUPERSEDED` merely because a newer publish arrives. Already-admitted work remains governed by its captured Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple and normal persistence, handoff, and execution fences until explicit repin or rollback, or fence rejection. -- **Current implementation status:** `PublishScriptPatchVersion` accepts the caller-supplied `baseVersionId` without proving same-tenant ownership, an eligible published state, or release evidence. `ResolveLaunchDescriptor` and Game Session `StartSession` also do not currently prove that a selected patch is published for and targets the resolved base version, or that Automation reports `READY`; a full-version template/request can therefore persist an arbitrary patch identity on the descriptor and instance. `GetPublishedScriptPatchVersion` and its patch digest lookup now require the exact `(tenantId, baseVersionId, scriptPatchVersion)` tuple and one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. Automation projections that do not yet retain base identity fail this lookup closed rather than selecting by patch name. These read filters do not establish complete publication or readiness; the remaining write, projection, and launch gaps are target-state work. +- **Current implementation status:** New publication remains unavailable without the required manifest and base compatibility authority. Descriptor creation and retained reads reject nonblank patches without exact publication and readiness evidence. The bounded failures and retained-history behavior are owned by [Version Control](version-control.md#script-patch-versions-and-runtime-behavior); [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment) records the remaining manifest, projection, production Temporal and activation gaps. - **Target state:** The Game Design Service queries readiness via a read-only API such as `GetScriptPatchStatus(tenantId, scriptPatchVersion)` and consumes the owner-provided rollout read for creator visibility so that UIs can show: - That a patch is published but still **pending runtime validation**. - The patch's `baseVersionId` and `abilitySchemaDigest` used for runtime compatibility gates and pinning checks. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 26b41dfe71..5964deb9c4 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -102,7 +102,7 @@ The following implementation and proof gaps remain in these live paths: - `PublishedReleaseBundle` retains `tenantId` in the entity/DTO but the current proto has no tenant field and the gRPC mapper does not emit it. Consumers cannot exact-compare the requested `(tenantId, versionId)` against the returned attestation; the target deterministic tenant/version response and fail-closed consumer comparison remain unimplemented. - `UploadPluginBundle` parses and verifies bytes before it creates a durable publication row or status event. Parse, malformed-manifest, archive-limit, and signature failures therefore cannot produce the target `UPLOAD_REJECTED` row/event, and the request has no stable retry identity or pre-parse raw-upload digest. The target intake boundary must durably record an attempt/rejection before or alongside parsing and compute `rawUploadDigest` as `sha256:<64 lowercase hexadecimal characters>` (SHA-256 over the exact received bytes, with no archive normalization, decompression, or transport metadata) under positive `rawUploadDigestSchemaVersion=1` before archive parsing; the normalized request binds that digest and schema version to the tenant and stable request identity. This raw-upload digest is distinct from the post-parse `bundleDigest` over canonical extracted entries. An identifiable plugin version may receive `UPLOAD_REJECTED`, while malformed or unidentifiable input must remain a tenant/request-scoped durable rejection without inventing plugin identity; exact retries replay only when the complete binding, including the raw-upload digest and schema version, matches, and changed request digests conflict. Focused proof for both identifiable and unidentifiable rejection is absent. -The current script-patch publication/read path is also narrower than the target contract: publication accepts an unvalidated caller-supplied `baseVersionId`, and publication reuse must preserve the effective `(tenantId, baseVersionId, scriptPatchVersion)` identity. Tenant readiness remains keyed by `(tenantId, scriptPatchVersion)` while separately validating immutable `baseVersionId` context, as defined in [Version Control](version-control.md#script-patch-versions-and-runtime-behavior); a separate script-only publication `versionId` is metadata/history and must not be substituted for `baseVersionId`. Game Design now rejects a new publish request when a retained script-only row already owns the effective tenant/base/patch tuple; V27 fails closed on retained incomplete or duplicate tuples and installs partial uniqueness without selecting or deleting a winner. Exact same-request replay still resolves its durable attempt first. Launch resolution and `StartSession` do not prove same-base published patch identity or Automation `READY`. `GetPublishedScriptPatchVersion` requires the complete tuple and its service/digest lookups require exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. Callers without authoritative base context fail closed. Notification transport and response failures are swallowed without a durable redrive. The remaining publication, projection, and readiness gaps mean the live APIs must not be treated as complete patch publication or launch-readiness authorities. +Script-patch publication is contained by the [manifest, retained-attempt and launch-evidence contract](version-control.md#script-patch-versions-and-runtime-behavior). New attempts cannot publish without an owner-verified handler manifest and return typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification, retaining the canonical Draft tuple and terminal failure. Prior PENDING attempts remain for reconciliation; historical success replay does not redispatch. The Automation client surfaces response rejection and preserves identifiable empty-handler dispatch to the readiness owner. Source-bound descriptor creation, retained replay and exact readback refuse nonblank patches without exact published-for-base and Automation `READY` evidence. `GetPublishedScriptPatchVersion` still requires the complete `(tenantId, baseVersionId, scriptPatchVersion)` tuple and exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. These guards do not implement a manifest producer, complete base-version authorization, readiness convergence, or player activation. Current proof limits belong to [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). The target tenant-scoped `GetTemplateReferencePhase` RPC is not implemented: it has no current proto RPC or registered handler. Prepared owner-local reference-phase storage and reads remain unregistered and confer no live launch or retirement authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 238b4f5ab9..3636ed91c0 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -314,7 +314,9 @@ opaque JSON blobs or service-specific payloads. Script-only fixes are tracked as `scriptPatchVersion` values attached to a `baseVersionId`. Together, `(baseVersionId, scriptPatchVersion)` identify the effective published script artifact and its base-cohesion/cache context for a game. A script-only publication may also receive a separate `versionId` for publication metadata and history; that identifier does not replace the base-version/patch pair when resolving the effective script artifact. The Game Design owner now rejects a new publish request when any retained script-only row already owns the same tenant/base/patch tuple, and V27 fails closed on retained incomplete or duplicate tuples before installing the matching partial unique index; it does not choose or delete a retained winner. A same-request retry continues through its durable publish-attempt outcome before that tuple-conflict check. For a V25 legacy script-patch quarantine that leaves a `FAILED` attempt and candidate after the original `PENDING` request digest could not be recovered, the original request cannot safely be replayed because the attempt cannot establish same-request identity without its stable digest. Publish any replacement with a new `scriptPatchVersion` and retain the quarantined candidate and attempt; the retained candidate continues to reserve its tenant/base/patch tuple. Dispose of an abandoned candidate only after the Game Design data owner proves it is an abandoned `DRAFT` under the [V27 migration preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight), including that no release bundle, active/launch/remap dependency, dependent publish attempt, or artifact workflow still requires it. That proof must account for the retained attempt and its dependencies; removal is an owner-approved disposition, not automatic quarantine cleanup. Exact publication metadata lookup requires one script-only row for the tenant/base/patch tuple in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state; new Game Session pin admission remains independently `PUBLISHED`-only. The accepted Game Session runtime execution pin and rollback fence remain the exact `{scriptPatchVersion, scriptPinEpoch}` tuple; `baseVersionId` is separately validated as the patch's base-cohesion and artifact context and does not silently add a field to Trigger Identity or replace that pin tuple. Artifact, cache, and runtime-read contracts that resolve an effective script artifact must carry and exact-compare the base-version/patch pair; the tenant readiness lifecycle and its readiness identity remain keyed by `scriptPatchVersion` as defined by Automation & Scripting's canonical lifecycle. -The current script-patch publication path retains a deterministic failure's Draft candidate and immutable identity with a stable FAILED attempt; exact replay reads that failure, and the retained tuple is not automatically reusable. +Script-patch publication must prove the immutable owner-verified affected-script/handler manifest before notification or publication success. An absent manifest fails with bounded `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before dispatch. A newly reserved attempt may record that failure while retaining its canonical Draft candidate and tuple; exact replay reads its terminal outcome. A pre-existing PENDING attempt is potentially dispatched evidence and requires reconciliation rather than redispatch or cleanup inferred from manifest absence. Historical SUCCEEDED replay does not send another notification. Identifiable empty-handler notifications remain dispatchable to the Automation readiness owner for the durable outcome required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md); transport acceptance never substitutes for manifest or `READY` proof. + +Launch selection, retained descriptor replay and exact descriptor readback require exact published-for-base patch identity and canonical Automation `READY` evidence. Without that evidence, a nonblank patch fails with `SCRIPT_PATCH_NOT_READY`; a retained digest alone cannot authorize its use. Unpatched descriptors retain their existing source, immutable request/result and release checks. Current source and unrun proof status are recorded in [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). The exact tuple propagation is now live across the instance-bound trigger, work-item, schedule/timer, projection, and replay surfaces. The deliberately extracted remote handoff/final-effect boundaries and complete Game Session rollout-history guarantees described below remain implementation/proof gaps; status is tracked in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). diff --git a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md index e09114a7c6..152b3a68a0 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -103,7 +103,7 @@ The required Trigger Identity fields and target-scope exceptions are defined in Only after all applicable handler-scoped gates pass does each admitted resolved handler create a durable parent work item, and its DSL run executes within that parent. A trigger with no admitted handlers creates no parent work items. The exact per-handler gates remain owned by [Normative Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). **Target state only:** after `EVALUATED_COMMITTED`, a work item gains immutable descriptor children and dispatches them through queue-pointer projections; target queue staging retains and exact-validates authoritative `playableStateNamespaceId` and separately validates `playableStateScope`. Current descriptor persistence and post-DSL dispatch/replay are unimplemented (see [Implementation Status](#implementation-status)); the current queue is only a pre-DSL parent-work pointer, and its instance-tagged key, work item/pointer, and outbox-ID-only claim do not establish namespace isolation. Target Automation dispatch turns committed descriptors into tick commands for the Game Session Service. -This is an overview rather than an exhaustive lifecycle. **Target state only:** an identifiable readiness notification whose immutable manifest proves zero `onLoad` handlers takes a direct terminal readiness-record path with `status=READY` and readiness-level evidence; one whose zero-handler claim lacks verifiable immutable proof attempts a direct terminal readiness-record path with `status=FAILED` and `statusReason=zero_handler_manifest_unverifiable`, subject to the readiness terminalization CAS. If that CAS loses because the same readiness identity is already terminal (`READY`, `FAILED`, or `SUPERSEDED`), the later proof result is a no-op and cannot relabel the prior terminal outcome, including after a newer publish supersedes the candidate. Neither path creates synthetic `onLoad` handler work or a handler audit row. **Current implementation:** the notification wire has no immutable manifest-proof or handler-count fields; an empty `affectedScripts` notification returns without creating readiness, while the current projection's integer count path records `READY` with `statusReason=no_scripts_in_patch` and does not expose proof or declared/terminal counts. +This is an overview rather than an exhaustive lifecycle. **Target state only:** an identifiable readiness notification whose immutable manifest proves zero `onLoad` handlers takes a direct terminal readiness-record path with `status=READY` and readiness-level evidence; one whose zero-handler claim lacks verifiable immutable proof attempts a direct terminal readiness-record path with `status=FAILED` and `statusReason=zero_handler_manifest_unverifiable`, subject to the readiness terminalization CAS. If that CAS loses because the same readiness identity is already terminal (`READY`, `FAILED`, or `SUPERSEDED`), the later proof result is a no-op and cannot relabel the prior terminal outcome, including after a newer publish supersedes the candidate. Neither path creates synthetic `onLoad` handler work or a handler audit row. **Current implementation:** the notification wire has no immutable manifest-proof or handler-count fields; an empty `affectedScripts` notification reports rejection without creating readiness, while the current projection's integer count path records `READY` with `statusReason=no_scripts_in_patch` and does not expose proof or declared/terminal counts. --- @@ -307,7 +307,7 @@ Two services collaborate to deliver scripting and automation: - Writes the final, validated script graphs and bindings into its own tables. - Validates that referenced runtime assets such as abilities and actions are compatible with the target game version; if mismatches are detected, publication fails and the affected `scriptPatchVersion` is never eligible to become `READY` for that tenant. - Publishes the immutable design-time patch and calls `NotifyScriptVersionUpdate` so Automation & Scripting ingests the compiled definitions, event bindings, and any world-generation hooks for the target ``. - - For an eligible non-empty handler notification, Automation & Scripting starts or reuses the durable Temporal `script-patch-readiness` workflow, which tracks validation and `onLoad` processing to terminal readiness without conflating publication with runtime admission. **Target state only:** when the immutable patch manifest verifiably declares zero `onLoad` handlers, Automation instead creates and exposes a terminal `READY` record carrying the pinned manifest reference/digest and zero declared and terminal handler counts, without a Temporal workflow or synthetic handler work. For an identifiable notification whose zero-handler claim lacks verifiable immutable proof, the readiness owner attempts to create and expose a durable `FAILED` record with a bounded `zero_handler_manifest_unverifiable` reason and readiness status/audit evidence, subject to the first-terminal readiness CAS; an already terminal `READY`, `FAILED`, or `SUPERSEDED` identity remains unchanged, including when a newer publish has superseded it. It does not silently reject or retry the DSL. **Current implementation:** the notification has no manifest-proof/count fields; an empty `affectedScripts` input creates no readiness, and the integer count path uses `READY`/`no_scripts_in_patch` without proof fields. + - For an eligible non-empty handler notification, Automation & Scripting starts or reuses the durable Temporal `script-patch-readiness` workflow, which tracks validation and `onLoad` processing to terminal readiness without conflating publication with runtime admission. **Target state only:** when the immutable patch manifest verifiably declares zero `onLoad` handlers, Automation instead creates and exposes a terminal `READY` record carrying the pinned manifest reference/digest and zero declared and terminal handler counts, without a Temporal workflow or synthetic handler work. For an identifiable notification whose zero-handler claim lacks verifiable immutable proof, the readiness owner attempts to create and expose a durable `FAILED` record with a bounded `zero_handler_manifest_unverifiable` reason and readiness status/audit evidence, subject to the first-terminal readiness CAS; an already terminal `READY`, `FAILED`, or `SUPERSEDED` identity remains unchanged, including when a newer publish has superseded it. It does not silently reject or retry the DSL. **Current implementation:** the notification has no manifest-proof/count fields; an empty `affectedScripts` input reports rejection and creates no readiness, and the integer count path uses `READY`/`no_scripts_in_patch` without proof fields. - On readiness failure, the patch remains published but ineligible for runtime use, and the prior exact Game Session pin remains in use for the game. - **Automation & Scripting Service** @@ -337,7 +337,7 @@ At a high level: The intended invariants are: -- A script patch may be pinned for a game only after Automation has loaded and validated that exact patch for the tenant and marked it `READY` as part of the readiness lifecycle. An eligible non-empty notification reaches `READY` through the readiness workflow. **Target state only:** a verified zero-onLoad-handler patch reaches terminal `READY` without a workflow or synthetic handler work, with its pinned manifest reference/digest and zero declared and terminal handler counts recorded and exposed; missing or unverifiable manifest proof cannot establish `READY`. **Current implementation:** the wire cannot carry or expose that proof; empty `affectedScripts` creates no readiness, while the integer count path can record `READY`/`no_scripts_in_patch` without proof. Workflow metadata is therefore optional only in the target proof-based zero-handler path. +- A script patch may be pinned for a game only after Automation has loaded and validated that exact patch for the tenant and marked it `READY` as part of the readiness lifecycle. An eligible non-empty notification reaches `READY` through the readiness workflow. **Target state only:** a verified zero-onLoad-handler patch reaches terminal `READY` without a workflow or synthetic handler work, with its pinned manifest reference/digest and zero declared and terminal handler counts recorded and exposed; missing or unverifiable manifest proof cannot establish `READY`. **Current implementation:** the wire cannot carry or expose that proof; empty `affectedScripts` reports rejection and creates no readiness, while the integer count path can record `READY`/`no_scripts_in_patch` without proof. Workflow metadata is therefore optional only in the target proof-based zero-handler path. - When Game Session emits gameplay/runtime events, it includes the exact currently pinned version and epoch. When Automation's scheduler admits a timer due candidate, it captures and propagates that exact tuple through the due candidate, firing claim, and resulting scheduler event. Automation must **not** silently substitute a different version or epoch; unknown, failed, stale, or mismatched authority rejects that trigger. Control-plane events lacking an epoch remain governed by their own control-plane contract rather than being rejected for that omission. From the Automation & Scripting Service’s point of view, each `` follows the readiness lifecycle described in [Script Patch Lifecycle](#script-patch-lifecycle). Runtime script-event audit entries include the effective exact `(scriptPatchVersion, scriptPinEpoch)` tuple at evaluation so operators can correlate failures with the authoritative instance pin; tenant `onLoad` readiness records have no instance pin epoch. diff --git a/design/architecture/system-architecture-scripting.md b/design/architecture/system-architecture-scripting.md index 74c8f420d3..4bc570a828 100644 --- a/design/architecture/system-architecture-scripting.md +++ b/design/architecture/system-architecture-scripting.md @@ -28,11 +28,11 @@ The live Automation runtime provides durable work-item execution, per-script quo - **Implemented and in active use** - The current Automation & Scripting runtime, including per-script quota and aggregate tenant-tier counters, durable work-item execution, structured command-template evaluation with narrow output, target, and DSL-shape checks, and best-effort queue-pointer projection; current queue reset/rebuild/resume is unavailable and fail-closed, while atomic owner-reconciled pre-DSL `PENDING_EVALUATION` recovery remains target-only. - - Hot reloading of scripts published by the Game Design Service for non-empty `affectedScripts` notifications, with version-aware script execution aligned with the versioning model in [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md#script-only-patch-versions). The current normal Game Design publication sends an empty list and therefore does not create readiness state or reload scripts; the target zero-handler path requires immutable manifest proof as described below. + - Hot reloading of scripts published by the Game Design Service for non-empty `affectedScripts` notifications, with version-aware script execution aligned with the versioning model in [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md#script-only-patch-versions). Current Game Design patch publication refuses before notification when participant or immutable manifest evidence is unavailable; this containment does not establish reload or readiness. Current proof and remaining owner work are recorded in the [Automation tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md). - **Implemented and evolving** - For non-empty notifications, the script publish lifecycle integrates Game Design publish workflows with Automation runtime reload and readiness gating (`PENDING_VALIDATION` -> `ONLOAD_RUNNING` -> `READY`/`FAILED`, with `SUPERSEDED` for older pending patches displaced by newer publishes). Newer-publish supersession is separate from stale executor recovery: the former terminalizes the older readiness patch as `SUPERSEDED`, while stale `ONLOAD_RUNNING` executor work remains unreclaimed in the current implementation. - - The tenant patch-readiness lifecycle has a Temporal `script-patch-readiness` workflow family for eligible non-empty `NotifyScriptVersionUpdate` notifications; the canonical patch-status control-plane reads expose workflow identity and execution status directly rather than relying on process-local orchestration state. The current normal Game Design integration sends an empty `affectedScripts` list, so Automation returns before creating a readiness row and the conditional workflow start is skipped; publication therefore has no readiness candidate or workflow. This empty-list path is an implementation gap, not successful readiness: unless the immutable patch manifest has been verified to declare zero `onLoad` handlers, an identifiable tenant/patch notification must create a durable `FAILED` readiness record with bounded reason `zero_handler_manifest_unverifiable` and status/audit evidence. Only a proven zero-handler manifest may complete without handler work, and the mandatory `onLoad` gate is never bypassed; an unidentifiable malformed notification may fail transport validation without fabricating patch identity. + - The tenant patch-readiness lifecycle has a Temporal `script-patch-readiness` workflow family for eligible non-empty `NotifyScriptVersionUpdate` notifications; the canonical patch-status control-plane reads expose workflow identity and execution status directly rather than relying on process-local orchestration state. Current Game Design publication stops before notification when required evidence is unavailable. A direct empty-list notification reports rejection without creating a readiness row or workflow; the required durable failure owner remains unimplemented. This empty-list path is an implementation gap, not successful readiness: unless the immutable patch manifest has been verified to declare zero `onLoad` handlers, an identifiable tenant/patch notification must create a durable `FAILED` readiness record with bounded reason `zero_handler_manifest_unverifiable` and status/audit evidence. Only a proven zero-handler manifest may complete without handler work, and the mandatory `onLoad` gate is never bypassed; an unidentifiable malformed notification may fail transport validation without fabricating patch identity. - World generation and PvE behavior libraries remain target-state/design areas; feature-level progress is tracked in service task lists rather than this hub. - Scheduler leadership leases and per-region tick-stream consumption are implemented; sharding/indexing and long-term retention jobs continue to evolve (see **Scheduler Leadership & Coordination** in `design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md` and the Automation & Scripting Service README for current behavior). @@ -116,7 +116,7 @@ At a high level, a script (or plugin) must pass through several stages before it - **Current publication boundary:** Game Design does have a design-time script-patch publication path through [`VersionServiceImpl`](../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java), but the owning authoring tracker records broader authoring/publication capability as partial and a published patch is only a readiness candidate; publication does not prove the target visual graph, loop-safety, or runtime readiness gates. Automation's tenant readiness remains the later `PENDING_VALIDATION` -> `ONLOAD_RUNNING` -> `READY`/`FAILED` lifecycle. 3. **`onLoad` initialization (Automation & Scripting Service, per tenant patch)** - - **Target state:** For each ``, the Automation & Scripting Service runs any configured `onLoad` handlers after static validation succeeds but **before** the patch is marked `READY` for that tenant. `READY` only means the patch is eligible for pinning; runtime admission, timers, reload pause, and rollback remain instance-scoped. **Current status:** the normal Game Design notification sends an empty `affectedScripts` list and the live Automation path returns before creating readiness state or running this lifecycle; it therefore does not establish reload, `READY`, or pin evidence. This current early return is not readiness proof; the target handler-free exception and its required manifest-backed terminal record are defined below. + - **Target state:** For each ``, the Automation & Scripting Service runs any configured `onLoad` handlers after static validation succeeds but **before** the patch is marked `READY` for that tenant. `READY` only means the patch is eligible for pinning; runtime admission, timers, reload pause, and rollback remain instance-scoped. **Current status:** contained Game Design publication fails before notification without required evidence, and direct empty-list notification rejection creates no readiness state or lifecycle. Neither result establishes reload, `READY`, or pin evidence; the target handler-free exception and its required manifest-backed terminal record are defined below. - In the first implementation slice, `onLoad` is limited to **ephemeral readiness work** such as validating configuration and warming recomputable in-process caches. It is not a hook for creating durable shared state. - Under [ADR 0115](./decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md), the immutable patch manifest is the authority for the expected `onLoad` handler set, including an explicit empty set. Readiness is `READY` only after every declared handler reaches its successful logical terminal outcome; observed work cannot be inferred as complete. When the manifest proves zero handlers, the readiness owner may create and expose a terminal `READY` record as pin-readiness proof without synthetic handler work or a synthetic readiness workflow; that record carries the immutable manifest reference/digest and zero declared and terminal handler counts. Each handler reuses its stable retry identity and deterministic `scriptEventId`, and only a greater accepted-publication sequence supersedes an older candidate; a late completion from an older sequence cannot reopen readiness. Cache warming remains recomputable, and durable game initialization belongs to its owning migration, publication, cutover, or instance workflow. - `onLoad` is a **mandatory gate**: if it fails with a logical or sandbox-level error, the patch is marked `FAILED` for that tenant, running instances remain on their previously pinned patch, and events referencing the failed patch are rejected with outcomes such as `version_unavailable`. The DSL evaluation itself is at-most-once and is never retried. Independently idempotent external infrastructure steps may retry transient failures only with the same persisted step identity, within an explicit maximum-attempts, maximum-elapsed-time/deadline, and bounded exponential-backoff-with-jitter budget; exhaustion records a terminal readiness failure and cannot advance the patch to `READY`. diff --git a/design/architecture/system-architecture-temporal-workflows.md b/design/architecture/system-architecture-temporal-workflows.md index 2590cff8cf..103b7cfb24 100644 --- a/design/architecture/system-architecture-temporal-workflows.md +++ b/design/architecture/system-architecture-temporal-workflows.md @@ -12,7 +12,7 @@ Current status (non-authoritative summary; [Shared Runtime, Service Contracts, a - services opt in through the shared Gradle plugin `net.firedevops.firemud.temporal-conventions`; - World Management now hosts the first real adopter through the `world-lifecycle` workflow family; - Game Design now hosts the durable `publish` workflow family for full-version publish and release-attestation orchestration, while exposing workflow runtime metadata through `GetPublishedReleaseBundle`; -- Automation Scripting hosts the `script-patch-readiness` workflow family for eligible non-empty `NotifyScriptVersionUpdate` notifications and durable `onLoad`/readiness progression. Target behavior reloads the complete notified patch through validation and `onLoad` to tenant `READY` before Game Session may pin or progress to it; Temporal coordinates that workflow but never becomes pin authority. Under [ADR 0115](./decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md), an immutable manifest that proves zero handlers may complete readiness as terminal `READY` with no synthetic handler work or workflow; an identifiable notification without that proof records terminal `FAILED` with bounded reason `zero_handler_manifest_unverifiable`. The current normal Game Design integration sends an empty `affectedScripts` list, so Automation returns before creating a readiness row and the conditional workflow start is skipped; that publication has no readiness candidate or workflow and cannot establish reload, `READY`, or pin evidence. +- Automation Scripting hosts the `script-patch-readiness` workflow family for eligible non-empty `NotifyScriptVersionUpdate` notifications and durable `onLoad`/readiness progression. Target behavior reloads the complete notified patch through validation and `onLoad` to tenant `READY` before Game Session may pin or progress to it; Temporal coordinates that workflow but never becomes pin authority. Under [ADR 0115](./decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md), an immutable manifest that proves zero handlers may complete readiness as terminal `READY` with no synthetic handler work or workflow; an identifiable notification without that proof records terminal `FAILED` with bounded reason `zero_handler_manifest_unverifiable`. Current Game Design patch publication stops before notification without required participant or immutable manifest evidence. Direct empty-list notification reports rejection without readiness or workflow creation; the target durable failure record remains unimplemented. See the [Automation tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md) and [Game Design tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) for local proof and remaining owner work. - `common-saga` remains the canonical substrate for short synchronous orchestration that does not need durable workflow execution. The World Management `world-lifecycle` family is the concrete lifecycle adopter governed by [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Temporal coordinates prepare, activation, failure, termination, retries, waits, and operator progress; World Management's durable lifecycle row and epoch remain the authority for `PREPARING`, `ACTIVE`, `FAILED_PRE_ACTIVATION`, `TERMINATING`, and `TERMINATED`. **Target-only:** owner cleanup acknowledgements are to be read from durable owner state before final termination. The current implementation has only a synchronous termination seam that calls Entity cleanup and hard-deletes a partial World runtime-row subset; it does not yet persist or read the frozen all-owner cleanup snapshot and per-owner acknowledgements required by ADR 0123. Routine gameplay/tick paths never query Temporal or wait on cleanup. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c506fafbe4..6510ac41f0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -15,4 +15,4 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. - `2026-11-01` (Pacific/Auckland): CI wait pending-status attribution requires separate provider reads. - - On #3365, the successful Validation CheckRun coexisted with a pending same-name status linked to a later metadata run, while the actual substantive Validation run was still active. Root incorrectly reported a barrier failure before locating that run and corrected Overseer immediately. CI wait named the conflicting status but omitted its description and target URL, requiring separate provider reads to establish attribution. Next: expose those bounded attribution fields in the owning controller diagnostic; reported to FireController Worker. Pending is not evidence that CI failed. Outcome at 6:41am NZDT: the original full Validation completed and all five gates passed; the barrier cleared normally without repair or rerun. The remaining request is diagnostic attribution only. + - On #3365, the successful Validation CheckRun coexisted with a pending same-name status linked to a later metadata run, while the actual substantive Validation run was still active. Root incorrectly reported a barrier failure before locating that run and corrected Overseer immediately. CI wait named the conflicting status but omitted its description and target URL, requiring separate provider reads to establish attribution. Next: expose those bounded attribution fields in the owning controller diagnostic; reported to FireController Worker. Pending is not evidence that CI failed. Outcome at 6:41am NZDT: the original full Validation completed and all five gates passed; the barrier cleared normally without repair or rerun. The remaining request is diagnostic attribution only. Client `30a92252` subsequently improves the pending-context explanation and distinguishes the actual status and CheckRun identities; the collector still does not retain a status description/URL, so it cannot supply an original-run link. The updated role-bound CLI was verified on 1 November; no workflow change or restart was needed. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index d92a190f7d..1ab3681ed2 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -123,7 +123,9 @@ Queued player commands persist `targetEntityId`, `regionId`, `regionEpoch`, and Matched handlers materialize durable `script_work_items` with event, handler, source, plugin, routing, scope, quota, and admission provenance. Ordinary work can be claimed through the explicit `PENDING_EVALUATION` to `EVALUATING` transition, evaluated from persisted script definitions, canceled durably for patch/plugin rollback or drain, and dead-lettered/replayed under compatibility gates. Tenant-readiness `onLoad` follows readiness-owner terminalization and generic dead-letter replay rejects it with `onload_not_replayable`; stale readiness work remains unreclaimed. Handler-scoped `script_event_audit` rows remain distinct from ingress audit and record cancellation and terminal outcomes. -Current status: `VersionServiceImpl.publishScriptPatchVersion` in Game Design calls `AutomationScriptingClient.notifyScriptVersionUpdate`, which sends `NotifyScriptVersionUpdate` with an empty `affectedScripts` list. Automation's `ScriptVersionServiceImpl.notifyUpdate` returns before creating readiness state and skips the conditional `script-patch-readiness` Temporal tracking hook, so normal script-patch publication currently establishes neither a readiness candidate nor a workflow. Focused unit coverage proves the direct non-empty notification delegation/hook path and separately proves that an empty list skips that hook; it does not prove end-to-end readiness for normal publication. The non-empty path now rejects a missing or duplicate requested definition before readiness admission, but still lacks an immutable expected-handler manifest, swallows notification/response failures, and can reuse/latest-select across changed base or release identities; these gaps remain. Target ownership and the expected-handler/terminal-outcome contract are canonical in [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). +Current status: `VersionServiceImpl.publishScriptPatchVersion` in Game Design still sends an empty `affectedScripts` list. The Automation receiver now returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; no readiness row, synthetic handler work, or Temporal readiness workflow is created. The empty request is safely rejected, but this does not satisfy ADR 0115: an identifiable patch without verified zero-handler proof requires one durable `FAILED` readiness record with normal status/audit evidence. The existing `ScriptPatchReadinessProjectionService` has no failed-terminal operation for a missing/unverifiable manifest, while `beginPatchReadiness` interprets an empty script set as `READY`; therefore that operation cannot be safely composed from the current owner API. Adding it requires extending the readiness projection owner/repository and focused durable status/audit proof, outside this receiver-only slice. Non-empty notifications now propagate the returned readiness-admission boolean instead of unconditionally reporting success; accepted readiness still is not `READY`. The immutable expected-handler manifest, source publication sequence/base binding, notification failure recovery, and readiness recovery gaps remain. Target ownership and the expected-handler/terminal-outcome contract are canonical in [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). + +The registered `GetDraftDesignDigest` receiver now returns `UNSUPPORTED_SCOPE` for both full-version and script-patch requests after exact caller/request-binding validation. The existing full digest is tenant-wide and uses a synthetic commit marker; the helper patch digest does not establish the required owner-verified base-bound publication manifest. The separate selected-empty full-version reader remains unregistered. Exact version mapping and patch-manifest attestation remain blockers before either scope can return a publication digest. The readiness refresh path still needs explicit recovery for activity retry exhaustion so an `ONLOAD_RUNNING` projection cannot remain stranded; mixed live/dry-run proof must also ensure dry-run `onLoad` work cannot advance the live readiness projection. These remain target implementation and proof gaps. The readiness correction now stores a nullable canonical script-set manifest and nullable `readiness_generation` in V2 so retained V1 projections remain readable but cannot be replayed without their original evidence. New identities receive a tenant-local generation under the readiness advisory lock; this is only the current-projection fence and does not provide the source accepted-publication sequence required by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). Retries compare the exact sorted script set, and legacy rows with no manifest or generation fail closed. The current-generation check, `onLoad` admission, schedule refresh, and pinned schedule reconciliation now run under one PostgreSQL transaction and shared tenant lock. A durable database progress bit is written in that transaction. A `READY` retry repairs schedule state without re-admitting `onLoad`; process-local registry rebuilding runs after that commit under a fresh lock and current-generation check. This closes the local check-then-effect race for a newer generation that is already accepted, but the notification contract still cannot distinguish a delayed older source publication from a newer one; source publication ordering, complete producer manifest, and base/request binding remain open. The partial unique index still rejects retained duplicate active rows rather than rewriting them. Focused unit proof covers changed-set rejection, newer-generation fencing, downstream failure, and `READY` retry behavior. PostgreSQL concurrency and rollback scenarios were not run by this bounded validation; this slice does not change Temporal workflow integration, empty-notification handling, source publication ordering, or readiness recovery. @@ -242,3 +244,5 @@ The evidence records focused proof for each live seam. Ingress and producer pari Handoff and remote authority proof is recorded in `ScriptGameplayCommandHandoffServiceImplTest`, `DefaultDurableRemoteFollowupExecutionServiceTest`, `RemoteFollowupRuntimeServiceImplTest`, and `GameSessionControlPlaneGrpcServiceTest`, including fail-closed provenance, contradictory metadata rejection, durable-row authority, remote trigger-event projection, and direct filtering. Operator/read-model proof includes `ScriptPatchReadinessProjectionServiceImplTest`, `ScriptWorkItemServiceImplTest`, `PluginRuntimeStateServiceImplTest`, `GameSessionPinControllerTest`, and `GameSessionPinServiceImplTest`. The observability proof covers the repo-owned scripting alert snippet and its core-alert index wiring. The recorded validation paths include focused service tests, `dev-tools/validation/run-locked-gradle.sh` service `check -PfullCheck` runs for Automation Scripting, Game Session, and Logging & Admin, `./gradlew linkCheck lintMarkdown`, and the handoff smoke proof `bash dev-tools/verify-fresh-bootstrap.sh`. + +R1420 local receiving proof passes all 50 selected Automation unit cases, including the unchanged NPC receiver after removal of dead digest-helper injection. The exact-scope digest receiver refuses rather than returning helper output; unsuccessful notification acceptance is propagated and does not start Temporal tracking. Enabled affected static analysis, full Java formatting, packaging and documentation checks pass as part of the combined 228-case gate with Game Design. These are component fixtures; manifest-backed readiness, the identifiable zero-handler durable failure/status/audit owner, monotonic acceptance and live pin/activation proof remain incomplete. Fresh source-built runtime qualification follows the current-parent carry. 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 8077e84c2c..e90ab41f3a 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 @@ -338,7 +338,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `EA-3.2` Creator authoring applications | `partial` | `audited` | [Frontend architecture](../../architecture/system-architecture-frontend.md); [creator journeys](../../product/user-journeys/creators.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md) | [App.tsx](../../../web-client/src/App.tsx); [GameEditor.tsx](../../../web-client/src/GameEditor.tsx); [ScriptEditor.tsx](../../../web-client/src/ScriptEditor.tsx); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java) | [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the [web-client README](../../../web-client/README.md) records a starter React surface and backend authoring APIs exist, but the designed creator application, accessible editor workflows, preview, conflict resolution, and focused frontend proof are absent. ADR 0124, ADR 0126, and ADR 0129 define the profile, scoped-proposal, and Draft-fence target behavior; implementation and focused proof remain absent. | | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | -| `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | +| `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake and bounded local activation-preflight/control-plane seams; new script-patch publication is contained pending manifest authority; 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; controlled five-store selected-full qualification commits the v4 bundle with the exact 4/3/1/6/2 participant vector and proves immutable readback/retry, as recorded above; public fresh/PENDING full-version publication and legacy bundle creation remain refused; 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. The bounded Entity/Automation selected-source intake and terminal-read slice has focused source/storage/transport proof at `f9e3f879d137b9a6fa54085e9c0b797586636a00`. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`; it is absent at `f9e3f879d137b9a6fa54085e9c0b797586636a00` and present at the later `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` Entity checkpoint. The current-source Entity execution at `17c82ab6462868a2f66dfe8a3cbc737bdd013383` passed 44 cases across seven suites in 67.986 seconds with zero failures, errors, or skips. Its 11-case physical PostgreSQL `EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow`; that test calls the Entity digest reader and compares the returned digest with an independently framed expected value. This was a focused gate, not a fresh whole-service Entity run. Separately, the exact-source Automation gate at `f2d3142214654736c224cb02f817d33f751b744d` passed 33 cases across eight suites in 75.453 seconds with zero failures, errors, or skips: 20 unit cases, nine physical PostgreSQL repository cases, three mocked service-integration cases, and one actual terminal-read mTLS/PostgreSQL case. The six-case physical PostgreSQL `AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest`. The earlier Entity attribution at `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` remains a separate historical checkpoint and is not part of the Automation aggregate. The Entity digest receiver unit result belongs to initial `e2c38ec63dc3664877ee0f7c8fb62ef6574777ce`: 917 Common, 187 Common Security, and 23 Entity unit cases passed on unchanged postimages, but that aggregate failed at test compilation. The receiver result does not establish a fresh whole-service aggregate. The slice remains standalone and unregistered; this proof does not establish complete owner publication, registration, or runtime activation. | [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); [Entity selected-source contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Automation selected-source contracts](../../architecture/microservices/automation-scripting-service/api-contracts.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); [EntityEmptySelectedSourceIntakeService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java); [EntityEmptySelectedSourceIntakeTerminalReadService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java); [EntitySelectedEmptyPublicationDigestService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java); [AutomationEmptySelectedSourceIntakeService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java); [AutomationEmptySelectedSourceIntakeTerminalReadService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java); [AutomationSelectedEmptyPublicationDigestService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [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); [EntityRetainedAuthoredActorCoreSourceServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java); [AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java); [EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java); [AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java); [EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [SelectedFullOwnerPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.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. Controlled selected-full qualification uses World digest schema 4 and a v4 bundle; exact retained v2/World-3 history remains readable. The owner components remain standalone and unregistered, with controlled authority inputs; public fresh/PENDING publication remains denied. 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. | @@ -417,10 +417,18 @@ Asset lifecycle status and proof remain partial: durable `version_asset` mapping 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. The retained full-Version gate and public participant observations still use World schema `3` and synthetic scope tokens; same-commit convergence remains incomplete. The separate controlled selected-full profile supports World schema `4` and its World4 lifecycle evidence, while the controlled Game Logic path can read the exact selected source against its immutable retained receipt. These capabilities do not supply production publication authority or close the remaining Game Logic owner-local manifest/provenance gap for full-version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The selected-full, digest and provenance target contract is owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile); the canonical candidate and asset lifecycle contracts are owned by [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. +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 prepared `VersionServiceImpl` containment refuses new patch publication without an owner-verified manifest before notification and does not start readiness, `onLoad`, rollout or supersede work; retained terminal success replay does not redispatch. Gameplay-time script execution and tick handoff remain outside Temporal. Temporal publication authorization has a distinct Game Design gRPC workload identity and guarded owner digest methods; the Automation digest no longer depends on a global admin role. The exact request/workflow/digest transaction and caller binding are implemented. Focused negative handler proof exists, but the real Temporal activity-to-Automation path, live certificate mounts, and denial of another internal workload remain unproved end to end. Normative owner-to-owner workload, tenant/scope, publication-request/workflow/request-digest binding, and script identity requirements are delegated to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization); this tracker records only current implementation and proof status. +### Script Patch Publication Containment + +The local receiving preparation preserves the stronger public full-publication authorization refusal and selected-full schema-4 operation/capture and release contracts. The old synchronous-fallback donor change is superseded by that denial. For patch publication, new reserved attempts pass the available participant gates but fail with typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification because no owner-verified handler manifest is available. Failure retains the current canonical DRAFT/tuple reservation; exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing PENDING originals remain potentially dispatched evidence needing reconciliation. Historical success replay performs no new notification. The Automation client surfaces rejected responses while allowing identifiable empty-handler notifications to reach the readiness owner governed by ADR 0115. + +New patched launch selection already fails closed. The receiving correction additionally refuses a retained patched descriptor after exact immutable request/source/result verification, for both replay and readback; it preserves valid unpatched resolution. No manifest, readiness receipt, digest, pin epoch or cleanup/release protocol is invented. Canonical semantics remain in [Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). + +Focused regression sources cover manifest refusal and retained failure/tuple custody, prior PENDING reconciliation, concurrent terminal outcomes, response rejection and empty-handler dispatch, and retained patched descriptor replay/readback. Validation: NONE; tests, compilation, formatting, static checks and documentation gates are deferred to the lane orchestrator. These authored regressions are not executed proof. Complete manifest production, readiness-owner convergence, production Temporal execution, and live player activation remain open. + ### Published Asset Lifecycle Current source/evidence status: Game Design has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes the frozen snapshot and records candidate manifest/artifact digests before object writes. Published repair independently reads an immutable candidate and checks it against the exact release bundle before object writes; this composed exporter/candidate/repair implementation has local source and unit proof, while migration closure and physical database/object-store execution remain unproved. Retired-version handling and end-to-end version-scoped readiness also remain unproved. @@ -507,3 +515,5 @@ No competing current authority is recorded for settings, versioned release bundl | Automation Scripting | Script patch readiness and plugin runtime activation, distinct from publication truth | Patch/readiness workflow and runtime pin/activation contracts | | Logging & Admin | Operator-facing compatibility and publication control-plane ingress | Canonical Game Design and runtime projections | | Temporal | Durable publish/readiness workflow execution where long-lived waiting is required | Workflow identity/status surfaced through canonical reads | + +R1420 local publication-containment proof passes 178 selected Game Design cases: 156 unit cases and 22 actual PostgreSQL/application cases, alongside 50 Automation units in the combined gate. The real patch owner records a manifest-unavailable terminal failure while retaining its canonical DRAFT tuple; exact retry preserves complete attempt/candidate rows and `xmin`, a genuine pre-existing PENDING original remains unchanged without redispatch, and the direct owner transaction rolls back its Draft/attempt writes together. Launch-descriptor SQL and current full-version offline transaction controls also pass. Participant gates are controlled collaborators, not genuine publication or manifest authority. Enabled affected static analysis, full formatting, both service packages and documentation checks pass; fresh source-built runtime proof remains pending on the carried parent. Existing full-publication authorization refusal, production manifest/readiness, Account/World source authority, recovery and activation holds remain. diff --git a/protos/automation-scripting/v1/README.md b/protos/automation-scripting/v1/README.md index 0dabe0d303..19f36b1a2a 100644 --- a/protos/automation-scripting/v1/README.md +++ b/protos/automation-scripting/v1/README.md @@ -21,7 +21,7 @@ RPC expectations: - `Ping` – safe to retry freely; no side effects. - `UpdateScript` – bootstrap/dev-only upload keyed by the stable `(tenant_id, version, name)` definition tuple; an exact transport retry reuses the same retained definition row/ID, while changed input replaces that tuple's definition and bindings atomically. The response reports success, not the row ID. v1 has no separate request ID for this operation, and it is not the production publication or rollout path. - `NotifyScriptVersionUpdate` – a patch-version notification for the publication-readiness workflow, not an `UpdateScript` retry. Its current wire lacks immutable manifest proof and an empty affected-script list does not establish readiness; see the readiness entry below. -- `GetScriptPatchStatus` / `ListScriptPatchStatuses` – visibility over tenant patch-readiness states, including linked Game Design publication metadata. The current wire enum still includes `SCRIPT_PATCH_STATUS_ROLLED_BACK`, and the current projection may emit `ROLLED_BACK` for canceled onLoad work as legacy drift. Current status responses have no immutable manifest-proof or declared/terminal-count fields, and the current empty `affectedScripts` path returns without creating readiness. The target lifecycle and manifest-proof vocabulary are defined by [ADR 0115](../../../design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). +- `GetScriptPatchStatus` / `ListScriptPatchStatuses` – visibility over tenant patch-readiness states, including linked Game Design publication metadata. The current wire enum still includes `SCRIPT_PATCH_STATUS_ROLLED_BACK`, and the current projection may emit `ROLLED_BACK` for canceled onLoad work as legacy drift. Current status responses have no immutable manifest-proof or declared/terminal-count fields. An empty notification now returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and creates no readiness row; ADR 0115's required durable `FAILED` record with status/audit evidence remains unimplemented. The target lifecycle and manifest-proof vocabulary are defined by [ADR 0115](../../../design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). - `SetAutomationAdmissionMode` – mutates the durable Automation-owned rollback admission barrier for one `(tenantId, gameInstanceId[, regionId])` scope and advances `admissionEpoch` when entering rollback pause. - `CancelPendingWorkItemsForPatch` / `CancelPendingWorkItemsForPluginVersion` – cancel not-yet-evaluating durable work items for script-patch or plugin-version rollback/disable scopes before they can hand off commands to Game Session. - `GetAutomationDrainStatus` – current rollback-drain visibility for one `(tenantId, gameInstanceId[, regionId])` scope, reporting `admissionMode`, `admissionEpoch`, active executions, cancelable pending work, `observedAtMs`, and `isStale` from durable admission/work-item state. @@ -64,7 +64,7 @@ The proto files in this directory define several RPCs consumed by domain service - `UpdateScript` – bootstrap/dev-only upload or atomic replacement of one `(tenant_id, version, name)` script definition and its event bindings; it is not the production publication handoff. Durable patch readiness for eligible non-empty `NotifyScriptVersionUpdate` notifications is tracked by the Temporal `script-patch-readiness` workflow rather than a publish Saga; the current wire/runtime cannot carry or expose immutable zero-handler manifest proof fields. The target lifecycle is defined by [ADR 0115](../../../design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). - `ScriptEventBinding.priorityTag` accepts the bounded tenant-budget tiers `high`, `normal`, and `background`; omitted values default to `normal`, and persisted handler work uses this tag when reserving live tenant execution budget. - `GetScriptStatus` – queries whether a script has queued or running work in the durable script work-item outbox. - - `NotifyScriptVersionUpdate` – informs the service that a new `script_patch_version` is available; the service reloads affected scripts, executes any required `onLoad` initialization, and updates its runtime registry. The current request has no immutable manifest reference/digest or handler-count proof fields, and an empty `affectedScripts` input currently returns without creating readiness. The target readiness lifecycle and manifest-proof requirements are defined by [ADR 0115](../../../design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). + - `NotifyScriptVersionUpdate` – informs the service that a new `script_patch_version` is available; the service reloads affected scripts, executes any required `onLoad` initialization, and updates its runtime registry. The current request has no immutable manifest reference/digest or handler-count proof fields. An empty `affectedScripts` input returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`, without synthetic work or a readiness row; the durable `FAILED` status/audit outcome required by ADR 0115 is not yet implemented. The target readiness lifecycle and manifest-proof requirements are defined by [ADR 0115](../../../design/architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). - **Event ingress APIs** - RPCs such as `TriggerScriptEvent` (or the actual event-ingress names defined here) are called by the Game Session Service and other domain services to deliver script events. Requests carry `tenantId`, `gameInstanceId`, resolved `playableStateScope`, `regionId`, and positive `regionEpoch` for gameplay/runtime and scheduler triggers (only an explicitly documented out-of-band consistency model may omit it), `entityId`, `scriptEventId`, `eventType`, `eventSchemaVersion`, the exact source `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple for instance-scoped triggers, `readSnapshotToken` when required by the registry, and an event payload envelope. Pre-instance ingress such as tenant-readiness `onLoad` omits `gameInstanceId` and all script-pin fields; explicitly unpinned epoch-zero records exist only on contracts that support that state and do not authorize instance-scoped trigger admission. For plugin triggers, requests also carry `pluginId` and `pluginVersionId`. - Event-ingress RPCs are **idempotent** with respect to Trigger Identity (including `scriptEventId`). The Automation & Scripting Service must deduplicate repeated deliveries using the rules described in `design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md#scripteventid-lifecycle-and-deduplication` and `design/architecture/system-architecture-scripting-contracts.md`. diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptVersionService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptVersionService.java index c348a37b4b..f38f026b41 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptVersionService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptVersionService.java @@ -4,6 +4,6 @@ /** Handles live script patch updates. */ public interface ScriptVersionService { - void notifyUpdate( + boolean notifyUpdate( String tenantId, long baseVersionId, String scriptPatchVersion, List affectedScripts); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java index a810096e2a..76beb2f4bf 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java @@ -13,7 +13,6 @@ import net.firedevops.firemud.automationscripting.service.NpcFormationService; import net.firedevops.firemud.automationscripting.service.PingService; import net.firedevops.firemud.automationscripting.service.ScriptDefinitionService; -import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService; import net.firedevops.firemud.automationscripting.service.ScriptEventIngressService; import net.firedevops.firemud.automationscripting.service.ScriptScheduleInstanceService; import net.firedevops.firemud.automationscripting.service.ScriptVersionService; @@ -62,7 +61,6 @@ public class AutomationScriptingGrpcService LoggerFactory.getLogger(AutomationScriptingGrpcService.class); private final PingService pingService; private final ScriptDefinitionService scriptService; - private final ScriptDesignDigestService scriptDesignDigestService; private final ScriptVersionService scriptVersionService; private final ScriptScheduleInstanceService scriptScheduleInstanceService; private final ScriptEventIngressService scriptEventIngressService; @@ -78,7 +76,6 @@ public class AutomationScriptingGrpcService public AutomationScriptingGrpcService( PingService pingService, ScriptDefinitionService scriptService, - ScriptDesignDigestService scriptDesignDigestService, ScriptVersionService scriptVersionService, ScriptScheduleInstanceService scriptScheduleInstanceService, ScriptEventIngressService scriptEventIngressService, @@ -88,7 +85,6 @@ public AutomationScriptingGrpcService( @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.pingService = pingService; this.scriptService = scriptService; - this.scriptDesignDigestService = scriptDesignDigestService; this.scriptVersionService = scriptVersionService; this.scriptScheduleInstanceService = scriptScheduleInstanceService; this.scriptEventIngressService = Objects.requireNonNull(scriptEventIngressService); @@ -382,37 +378,19 @@ public void getDraftDesignDigest( requirePublicationRead(); PublicationDigestRequestBinding binding = publicationBinding(request); binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); - long baseVersionId = 0L; - if (binding.scopeKind() == PublicationDigestRequestBinding.ScopeKind.SCRIPT_PATCH) { - baseVersionId = - RequestIdValidation.requirePositiveLong(binding.baseVersionId(), "baseVersionId"); - } - var digest = - binding.scopeKind() == PublicationDigestRequestBinding.ScopeKind.FULL_VERSION - ? scriptDesignDigestService.getDraftDesignDigestForVersion( - binding.tenantId(), binding.versionId()) - : scriptDesignDigestService.getDraftDesignDigestForScriptPatch( - binding.tenantId(), baseVersionId, binding.scriptPatchVersion()); - binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); - if (binding.scopeKind() == PublicationDigestRequestBinding.ScopeKind.SCRIPT_PATCH - && (digest.baseVersionId() <= 0L || baseVersionId != digest.baseVersionId())) { - throw new IllegalArgumentException( - "owner digest base_version_id does not match publication binding"); - } - GetDraftDesignDigestResponse.Builder response = + // The current helper digests do not prove exact published-version or base-bound patch + // content. Keep the authenticated receiver closed until those mappings are authoritative. + responseObserver.onNext( GetDraftDesignDigestResponse.newBuilder() - .setTenantId(binding.tenantId()) - .setAppliedCommitId(digest.appliedCommitId()) - .setContentDigest(digest.contentDigest()) - .setDigestSchemaVersion(digest.digestSchemaVersion()); - if (binding.scopeKind() == PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { - response.setVersionId(binding.versionId()); - } else { - response - .setScriptPatchVersion(binding.scriptPatchVersion()) - .setBaseVersionId(Long.toString(digest.baseVersionId())); - } - responseObserver.onNext(response.build()); + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetDraftDesignDigest", + "UNSUPPORTED_SCOPE", + "Automation cannot attest this scope until its exact version mapping " + + "and base-bound patch digest are available")) + .build()); responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { responseObserver.onNext( @@ -514,12 +492,22 @@ public void notifyScriptVersionUpdate( NotifyScriptVersionUpdateResponse.newBuilder(); try { requireAdminRole(); - scriptVersionService.notifyUpdate( - request.getTenantId(), - request.getBaseVersionId(), - request.getScriptPatchVersion(), - request.getAffectedScriptsList()); - response.setSuccess(true); + boolean readinessAccepted = + scriptVersionService.notifyUpdate( + request.getTenantId(), + request.getBaseVersionId(), + request.getScriptPatchVersion(), + request.getAffectedScriptsList()); + response.setSuccess(readinessAccepted); + if (!readinessAccepted) { + response.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "NotifyScriptVersionUpdate", + "FAILED_PRECONDITION", + "patch_readiness_not_current")); + } } catch (IllegalArgumentException ex) { response .setSuccess(false) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImpl.java index bee22ddf27..08b3a5302d 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImpl.java @@ -18,7 +18,7 @@ public ScriptVersionServiceImpl( } @Override - public void notifyUpdate( + public boolean notifyUpdate( String tenantId, long baseVersionId, String scriptPatchVersion, @@ -28,5 +28,6 @@ public void notifyUpdate( if (temporalOrchestrator.isPresent() && readinessActive) { temporalOrchestrator.get().startTracking(tenantId, scriptPatchVersion); } + return readinessActive; } } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java index 5c380d683b..94c6a3b79b 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java @@ -17,7 +17,6 @@ import net.firedevops.firemud.automationscripting.service.NpcFormationService; import net.firedevops.firemud.automationscripting.service.PingService; import net.firedevops.firemud.automationscripting.service.ScriptDefinitionService; -import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService; import net.firedevops.firemud.automationscripting.service.ScriptEventIngressService; import net.firedevops.firemud.automationscripting.service.ScriptScheduleInstanceService; import net.firedevops.firemud.automationscripting.service.ScriptVersionService; @@ -103,12 +102,10 @@ void clearSessionContext() { SessionContext.clear(); } - private AutomationScriptingGrpcService configuredService( - String workloadNamespace, ScriptDesignDigestService digestService) { + private AutomationScriptingGrpcService configuredService(String workloadNamespace) { return new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - digestService, Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -121,8 +118,7 @@ private AutomationScriptingGrpcService configuredService( @Test void missingOrInvalidConfiguredWorkloadNamespaceDeniesDigestReadBeforeOwnerRead() { for (String workloadNamespace : new String[] {null, "", " ", "not a namespace"}) { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); - AutomationScriptingGrpcService service = configuredService(workloadNamespace, digestService); + AutomationScriptingGrpcService service = configuredService(workloadNamespace); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); @@ -131,15 +127,12 @@ void missingOrInvalidConfiguredWorkloadNamespaceDeniesDigestReadBeforeOwnerRead( assertEquals( "PERMISSION_DENIED", invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); - Mockito.verifyNoInteractions(digestService); } - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - digestService, Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -154,29 +147,21 @@ void missingOrInvalidConfiguredWorkloadNamespaceDeniesDigestReadBeforeOwnerRead( assertEquals( "PERMISSION_DENIED", invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); - Mockito.verifyNoInteractions(digestService); } @Test - void getDraftDesignDigestSupportsVersionScope() { + void getDraftDesignDigestRejectsUnmappedVersionScope() { PingService pingService = Mockito.mock(PingService.class); ScriptDefinitionService scriptService = Mockito.mock(ScriptDefinitionService.class); - ScriptDesignDigestService scriptDesignDigestService = - Mockito.mock(ScriptDesignDigestService.class); ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); ScriptEventIngressService ingressService = Mockito.mock(ScriptEventIngressService.class); NpcFormationService formationService = Mockito.mock(NpcFormationService.class); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); - Mockito.when(scriptDesignDigestService.getDraftDesignDigestForVersion("1", "7")) - .thenReturn( - new ScriptDesignDigestService.ScriptDraftDesignDigest( - "1", "7", 0L, "version:7", "digest-script", 1)); AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( pingService, scriptService, - scriptDesignDigestService, versionService, Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -203,30 +188,22 @@ public void onError(Throwable t) {} public void onCompleted() {} })); - assertEquals("7", ref.get().getVersionId()); - assertEquals("version:7", ref.get().getAppliedCommitId()); + assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); } @Test - void getDraftDesignDigestSupportsBoundScriptPatchScope() { + void getDraftDesignDigestRejectsUnsupportedPatchScopeWithValidBaseBinding() { PingService pingService = Mockito.mock(PingService.class); ScriptDefinitionService scriptService = Mockito.mock(ScriptDefinitionService.class); - ScriptDesignDigestService scriptDesignDigestService = - Mockito.mock(ScriptDesignDigestService.class); ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); ScriptEventIngressService ingressService = Mockito.mock(ScriptEventIngressService.class); NpcFormationService formationService = Mockito.mock(NpcFormationService.class); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); - Mockito.when(scriptDesignDigestService.getDraftDesignDigestForScriptPatch("1", 7L, "patch:é:1")) - .thenReturn( - new ScriptDesignDigestService.ScriptDraftDesignDigest( - "1", "patch:é:1", 7L, "patch:patch:é:1", "digest-script-patch", 1)); AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( pingService, scriptService, - scriptDesignDigestService, versionService, Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -253,16 +230,12 @@ public void onError(Throwable t) {} public void onCompleted() {} })); - assertEquals("1", ref.get().getTenantId()); - assertEquals("7", ref.get().getBaseVersionId()); - assertEquals("patch:é:1", ref.get().getScriptPatchVersion()); - assertEquals("patch:patch:é:1", ref.get().getAppliedCommitId()); + assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); } @Test - void getDraftDesignDigestRejectsInvalidScriptPatchBaseBeforeOwnerRead() { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); - AutomationScriptingGrpcService service = configuredService(TEST_NAMESPACE, digestService); + void getDraftDesignDigestRejectsInvalidScriptPatchBaseBeforeUnsupportedScope() { + AutomationScriptingGrpcService service = configuredService(TEST_NAMESPACE); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); @@ -285,44 +258,11 @@ void getDraftDesignDigestRejectsInvalidScriptPatchBaseBeforeOwnerRead() { : "baseVersionId exceeds signed positive long range", response.get().getError().getMessage()); } - Mockito.verifyNoInteractions(digestService); - } - - @Test - void getDraftDesignDigestMapsOwnerBaseFailuresToFailedPrecondition() { - Map expectedCodes = - Map.of( - "script_patch_base_version_unavailable", "FAILED_PRECONDITION", - "script_patch_base_version_unavailable:script", "FAILED_PRECONDITION", - "script_patch_base_version_unavailable:binding", "FAILED_PRECONDITION", - "script_patch_base_version_mismatch:script", "FAILED_PRECONDITION", - "script_patch_base_version_mismatch:binding", "FAILED_PRECONDITION", - "script_patch_base_version_mismatch", "INVALID_ARGUMENT", - "unrelated_argument_error", "INVALID_ARGUMENT"); - SessionContext.setContext( - null, List.of(), Map.of(), true, "game-design-service", "test-instance"); - - expectedCodes.forEach( - (message, expectedCode) -> { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); - Mockito.doThrow(new IllegalArgumentException(message)) - .when(digestService) - .getDraftDesignDigestForScriptPatch("1", 7L, "patch-1"); - AutomationScriptingGrpcService service = configuredService(TEST_NAMESPACE, digestService); - - AtomicReference response = new AtomicReference<>(); - runAsGameDesign( - () -> response.set(invokeDigest(service, patchDigestRequest("1", "7", "patch-1")))); - - assertEquals(expectedCode, response.get().getError().getCode(), message); - assertEquals(message, response.get().getError().getMessage()); - }); } @Test void getDraftDesignDigestRejectsInactiveBaseVersionForFullScope() { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); - AutomationScriptingGrpcService service = configuredService(TEST_NAMESPACE, digestService); + AutomationScriptingGrpcService service = configuredService(TEST_NAMESPACE); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); @@ -332,17 +272,14 @@ void getDraftDesignDigestRejectsInactiveBaseVersionForFullScope() { runAsGameDesign(() -> ref.set(invokeDigest(service, request))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test void getDraftDesignDigestRejectsJwtOnlyCaller() { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - digestService, Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -368,17 +305,14 @@ public void onError(Throwable t) {} public void onCompleted() {} }); assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - digestService, Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -402,17 +336,14 @@ void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() { "42", List.of("platformAdmin"), Map.of(), false, "game-design-service", null); assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode()); }); - Mockito.verifyNoInteractions(digestService); } @Test - void getDraftDesignDigestRejectsWrongDigestBeforeOwnerRead() { - ScriptDesignDigestService digestService = Mockito.mock(ScriptDesignDigestService.class); + void getDraftDesignDigestRejectsWrongDigestBeforeUnsupportedScope() { AutomationScriptingGrpcService service = new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - digestService, Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -433,7 +364,6 @@ void getDraftDesignDigestRejectsWrongDigestBeforeOwnerRead() { .build()))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(digestService); } private GetDraftDesignDigestResponse invokeDigest( @@ -471,8 +401,6 @@ void pingReturnsPong() { PingService pingService = Mockito.mock(PingService.class); Mockito.when(pingService.ping()).thenReturn("pong"); ScriptDefinitionService scriptService = Mockito.mock(ScriptDefinitionService.class); - ScriptDesignDigestService scriptDesignDigestService = - Mockito.mock(ScriptDesignDigestService.class); ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); ScriptEventIngressService ingressService = Mockito.mock(ScriptEventIngressService.class); NpcFormationService formationService = Mockito.mock(NpcFormationService.class); @@ -480,7 +408,6 @@ void pingReturnsPong() { new AutomationScriptingGrpcService( pingService, scriptService, - scriptDesignDigestService, versionService, Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -513,8 +440,6 @@ void validationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); Mockito.when(pingService.ping()).thenThrow(new IllegalArgumentException("bad")); ScriptDefinitionService scriptService = Mockito.mock(ScriptDefinitionService.class); - ScriptDesignDigestService scriptDesignDigestService = - Mockito.mock(ScriptDesignDigestService.class); ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); ScriptEventIngressService ingressService = Mockito.mock(ScriptEventIngressService.class); NpcFormationService formationService = Mockito.mock(NpcFormationService.class); @@ -522,7 +447,6 @@ void validationErrorReturnsErrorDetail() { new AutomationScriptingGrpcService( pingService, scriptService, - scriptDesignDigestService, versionService, Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -557,8 +481,6 @@ void unexpectedErrorReturnsInternalResponse() { PingService pingService = Mockito.mock(PingService.class); Mockito.when(pingService.ping()).thenThrow(new RuntimeException("boom")); ScriptDefinitionService scriptService = Mockito.mock(ScriptDefinitionService.class); - ScriptDesignDigestService scriptDesignDigestService = - Mockito.mock(ScriptDesignDigestService.class); ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); ScriptEventIngressService ingressService = Mockito.mock(ScriptEventIngressService.class); NpcFormationService formationService = Mockito.mock(NpcFormationService.class); @@ -566,7 +488,6 @@ void unexpectedErrorReturnsInternalResponse() { new AutomationScriptingGrpcService( pingService, scriptService, - scriptDesignDigestService, versionService, Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -611,7 +532,6 @@ void triggerScriptEventReturnsAdmissionOutcome() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -665,7 +585,6 @@ void triggerScriptEventMapsActiveIngressClaimToRetryableUnavailableWithoutRespon new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -709,7 +628,6 @@ void triggerScriptEventReturnsInvalidArgumentAsTransportError() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), ingressService, @@ -753,7 +671,6 @@ void getScriptStatusUsesWorkItemOutbox() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -793,7 +710,6 @@ void notifyScriptVersionUpdateReturnsAppErrorForInvalidScheduleMetadata() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -828,6 +744,49 @@ public void onCompleted() {} assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } + @Test + void notifyScriptVersionUpdateDoesNotReportReadinessForEmptyAffectedScripts() { + ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); + Mockito.when(versionService.notifyUpdate("1", 1L, "patch-1", List.of())).thenReturn(false); + AutomationScriptingGrpcService service = + new AutomationScriptingGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(ScriptDefinitionService.class), + versionService, + Mockito.mock(ScriptScheduleInstanceService.class), + Mockito.mock(ScriptEventIngressService.class), + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(NpcFormationService.class), + new SimpleMeterRegistry(), + ""); + AtomicReference ref = new AtomicReference<>(); + + service.notifyScriptVersionUpdate( + NotifyScriptVersionUpdateRequest.newBuilder() + .setTenantId("1") + .setBaseVersionId(1L) + .setScriptPatchVersion("patch-1") + .build(), + new StreamObserver<>() { + @Override + public void onNext(NotifyScriptVersionUpdateResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("patch_readiness_not_current", ref.get().getError().getMessage()); + Mockito.verify(versionService).notifyUpdate("1", 1L, "patch-1", List.of()); + } + @Test void notifyScriptVersionUpdateMapsUnavailableBaseVersionArgumentToFailedPreconditionAppError() { ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); @@ -838,7 +797,6 @@ void notifyScriptVersionUpdateMapsUnavailableBaseVersionArgumentToFailedPrecondi new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -884,7 +842,6 @@ void notifyScriptVersionUpdateKeepsMismatchedBaseVersionArgumentInvalid() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -930,7 +887,6 @@ void notifyScriptVersionUpdateMapsUnavailableBaseVersionToFailedPreconditionAppE new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -976,7 +932,6 @@ void notifyScriptVersionUpdateMapsUnrelatedIllegalStateExceptionToInternalAppErr new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -1022,7 +977,6 @@ void notifyScriptVersionUpdateMapsActiveOnLoadClaimToRetryableUnavailableWithout new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), versionService, Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -1073,7 +1027,6 @@ void observeRuntimeTickProgressDelegatesToScheduleInstanceService() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), scheduleInstanceService, Mockito.mock(ScriptEventIngressService.class), @@ -1117,7 +1070,6 @@ void updateScriptRejectsZeroTenantIdBeforeUpdate() { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), scriptService, - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), @@ -1163,7 +1115,6 @@ void updateScriptRejectsOmittedBindingIdThroughGrpc() throws SagaException { new AutomationScriptingGrpcService( Mockito.mock(PingService.class), scriptService, - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/NpcFormationGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/NpcFormationGrpcServiceTest.java index 4648773398..5c61b6c0e4 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/NpcFormationGrpcServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/NpcFormationGrpcServiceTest.java @@ -14,7 +14,6 @@ import net.firedevops.firemud.automationscripting.service.NpcFormationService; import net.firedevops.firemud.automationscripting.service.PingService; import net.firedevops.firemud.automationscripting.service.ScriptDefinitionService; -import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService; import net.firedevops.firemud.automationscripting.service.ScriptEventIngressService; import net.firedevops.firemud.automationscripting.service.ScriptScheduleInstanceService; import net.firedevops.firemud.automationscripting.service.ScriptVersionService; @@ -310,7 +309,6 @@ private static AutomationScriptingGrpcService newService(NpcFormationService npc return new AutomationScriptingGrpcService( Mockito.mock(PingService.class), Mockito.mock(ScriptDefinitionService.class), - Mockito.mock(ScriptDesignDigestService.class), Mockito.mock(ScriptVersionService.class), Mockito.mock(ScriptScheduleInstanceService.class), Mockito.mock(ScriptEventIngressService.class), diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java index 4cc602f564..0c6e90ac88 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java @@ -146,7 +146,7 @@ void notifyUpdateRejectsDefinitionRetainedUnderDifferentBaseBeforeReadinessAdmis } @Test - void emptyAffectedManifestDoesNotMaterializeReadiness() { + void emptyAffectedScriptsReturnsNotAcceptedWithoutCreatingReadinessOrWork() { assertThat(service.notifyUpdate("1", 1L, "v1-script.1", List.of())).isFalse(); verifyNoInteractions( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImplTest.java index 6d2a13ed68..c73a73f79e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptVersionServiceImplTest.java @@ -1,7 +1,10 @@ package net.firedevops.firemud.automationscripting.service.impl; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -18,7 +21,7 @@ void notifyUpdateDelegatesToTemporalTrackingWhenAvailable() { new ScriptVersionServiceImpl(commandService, Optional.of(orchestrator)); when(commandService.notifyUpdate("1", 1L, "patch-1", List.of("guard-script"))).thenReturn(true); - service.notifyUpdate("1", 1L, "patch-1", List.of("guard-script")); + assertTrue(service.notifyUpdate("1", 1L, "patch-1", List.of("guard-script"))); verify(commandService).notifyUpdate("1", 1L, "patch-1", List.of("guard-script")); verify(orchestrator).startTracking("1", "patch-1"); @@ -35,9 +38,24 @@ void notifyUpdateSkipsTemporalTrackingWhenReadinessIsTerminal() { when(commandService.notifyUpdate("1", 1L, "patch-1", List.of("guard-script"))) .thenReturn(false); - service.notifyUpdate("1", 1L, "patch-1", List.of("guard-script")); + assertFalse(service.notifyUpdate("1", 1L, "patch-1", List.of("guard-script"))); verify(commandService).notifyUpdate("1", 1L, "patch-1", List.of("guard-script")); - org.mockito.Mockito.verifyNoInteractions(orchestrator); + verifyNoInteractions(orchestrator); + } + + @Test + void notifyUpdateReturnsNotAcceptedWithoutTemporalTrackingForEmptyManifest() { + ScriptPatchVersionCommandService commandService = mock(ScriptPatchVersionCommandService.class); + TemporalScriptPatchReadinessOrchestrator orchestrator = + mock(TemporalScriptPatchReadinessOrchestrator.class); + ScriptVersionServiceImpl service = + new ScriptVersionServiceImpl(commandService, Optional.of(orchestrator)); + when(commandService.notifyUpdate("1", 1L, "patch-1", List.of())).thenReturn(false); + + assertFalse(service.notifyUpdate("1", 1L, "patch-1", List.of())); + + verify(commandService).notifyUpdate("1", 1L, "patch-1", List.of()); + verifyNoInteractions(orchestrator); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/AutomationScriptingClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/AutomationScriptingClient.java index 4d1d8fc4d3..8840d1d267 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/AutomationScriptingClient.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/AutomationScriptingClient.java @@ -51,12 +51,12 @@ protected AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub AutomationScriptingServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - /** Notify the Automation service that a new script patch version is active. */ + /** + * Notify Automation of a published candidate; acceptance does not establish runtime activation. + */ public void notifyScriptVersionUpdate( String tenantId, Long baseVersionId, String patchVersion, List scripts) { - if (baseVersionId == null || baseVersionId <= 0) { - throw new IllegalArgumentException("baseVersionId must be positive"); - } + validateNotificationRequest(tenantId, baseVersionId, patchVersion, scripts); NotifyScriptVersionUpdateRequest request = NotifyScriptVersionUpdateRequest.newBuilder() .setTenantId(tenantId) @@ -64,7 +64,37 @@ public void notifyScriptVersionUpdate( .addAllAffectedScripts(scripts) .setBaseVersionId(baseVersionId) .build(); - stub().notifyScriptVersionUpdate(request); + var response = stub().notifyScriptVersionUpdate(request); + if (!response.getSuccess() || response.hasError()) { + String detail = response.hasError() ? response.getError().getCode() : "NO_READINESS_STARTED"; + throw new IllegalStateException( + "SCRIPT_PATCH_NOTIFICATION_REJECTED: Automation did not accept patch readiness: " + + detail); + } + } + + private void validateNotificationRequest( + String tenantId, Long baseVersionId, String patchVersion, List scripts) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException( + "SCRIPT_PATCH_NOTIFICATION_PRE_DISPATCH_INVALID: tenantId is required"); + } + if (baseVersionId == null || baseVersionId <= 0) { + throw new IllegalArgumentException( + "SCRIPT_PATCH_NOTIFICATION_PRE_DISPATCH_INVALID: baseVersionId must be positive"); + } + if (patchVersion == null || patchVersion.isBlank()) { + throw new IllegalArgumentException( + "SCRIPT_PATCH_NOTIFICATION_PRE_DISPATCH_INVALID: scriptPatchVersion is required"); + } + if (scripts == null) { + throw new IllegalArgumentException( + "SCRIPT_PATCH_NOTIFICATION_PRE_DISPATCH_INVALID: affectedScripts must be provided"); + } + if (scripts.stream().anyMatch(script -> script == null || script.isBlank())) { + throw new IllegalArgumentException( + "SCRIPT_PATCH_NOTIFICATION_PRE_DISPATCH_INVALID: affectedScripts contains a blank script"); + } } public PublishParticipantDigestDto getDraftDesignDigestForScriptPatch( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 10272df84a..aca63dc4c2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -474,6 +474,11 @@ private ResolvedLaunchDescriptorDto readStored( throw new IllegalArgumentException( "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); } + requireReadyScriptPatch( + request.requestedScriptPatchVersionPresent() + ? request.requestedScriptPatchVersion() + : null); + requireReadyScriptPatch(evidence.scriptPatchVersion()); return new ResolvedLaunchDescriptorDto( evidence.launchDescriptorId(), evidence.canonicalTenantId().toString(), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 61db98cdfe..17b6084ea4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -11,7 +11,6 @@ import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; -import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; @@ -64,6 +63,8 @@ public class VersionServiceImpl implements VersionService { private static final int DEFAULT_PLUGIN_VERSION_STATUS_LIMIT = 100; private static final int MAX_PLUGIN_VERSION_STATUS_LIMIT = 200; + private static final String RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE = + "PARTICIPANT_DEPENDENCY_UNAVAILABLE_RETRYABLE"; private static final Logger logger = LoggingUtil.getLogger(VersionServiceImpl.class); @@ -72,7 +73,6 @@ public class VersionServiceImpl implements VersionService { private final PublishedPluginVersionRepository publishedPluginVersionRepository; private final PluginVersionStatusEventRepository pluginVersionStatusEventRepository; private final VersionMapper versionMapper; - private final AutomationScriptingClient scriptingClient; private final PublishAttemptService publishAttemptService; private final PublishGateService publishGateService; private final ControlPlaneDigestService controlPlaneDigestService; @@ -91,7 +91,6 @@ public VersionServiceImpl( PublishedPluginVersionRepository publishedPluginVersionRepository, PluginVersionStatusEventRepository pluginVersionStatusEventRepository, VersionMapper versionMapper, - AutomationScriptingClient scriptingClient, PublishAttemptService publishAttemptService, PublishGateService publishGateService, ControlPlaneDigestService controlPlaneDigestService, @@ -107,7 +106,6 @@ public VersionServiceImpl( this.publishedPluginVersionRepository = publishedPluginVersionRepository; this.pluginVersionStatusEventRepository = pluginVersionStatusEventRepository; this.versionMapper = versionMapper; - this.scriptingClient = scriptingClient; this.publishAttemptService = publishAttemptService; this.publishGateService = publishGateService; this.controlPlaneDigestService = controlPlaneDigestService; @@ -172,50 +170,31 @@ public VersionDto publishScriptPatchVersion( throw ex.causeException(); } if (reservation.status() == PublishAttemptStatus.SUCCEEDED) { - notifyScriptPatchVersionUpdate(tenantId, baseVersionId, scriptPatchVersion); return reservation.versionDto(); } if (reservation.status() == PublishAttemptStatus.FAILED) { throw replayFailedScriptPatch(reservation.failureCode(), reservation.failureMessage()); } + if (!reservation.newlyCreated()) { + throw pendingScriptPatchReconciliation( + new ScriptPatchPublishFailureException( + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE", + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE: the prior publish attempt may have dispatched readiness without a verifiable affected-script manifest")); + } - boolean finalizationStarted = false; - boolean finalizationReturned = false; + boolean participantGatePassed = false; try { List participantDigests = publishGateService.collectScriptPatchParticipantDigests( reservation.versionDto(), patchBinding.publishRequestId(), publishWorkflowId); publishGateService.assertGatePassed(reservation.versionDto(), participantDigests); + participantGatePassed = true; recordedParticipantDigestService.assertMatchesRecordedDigests( tenantId, PublishType.SCRIPT_PATCH, participantDigests); - finalizationStarted = true; - ScriptPatchFinalization finalization = - publishAttemptService.executeScriptPatchTransaction( - () -> finalizeScriptPatch(patchBinding, reservation, participantDigests, tenantId)); - finalizationReturned = true; - if (finalization.status() == PublishAttemptStatus.SUCCEEDED) { - notifyScriptPatchVersionUpdate(tenantId, baseVersionId, scriptPatchVersion); - return finalization.versionDto(); - } - if (finalization.status() == PublishAttemptStatus.FAILED) { - throw replayFailedScriptPatch(finalization.failureCode(), finalization.failureMessage()); - } - throw pendingScriptPatchFinalization( - new IllegalStateException("finalization returned a pending publish attempt")); + throw new ScriptPatchPublishFailureException( + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE", + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE: the reserved patch has no owner-verified affected-script manifest"); } catch (RuntimeException ex) { - if (finalizationStarted && !finalizationReturned) { - if (ex instanceof PublishAttemptService.ScriptPatchTransactionException) { - // The transaction wrapper reports a definite failure from the callback. - } else { - // The transaction call did not return, so commit status is unknown. Keep the durable - // PENDING receipt for reconciliation rather than guessing whether cleanup is safe. - throw pendingScriptPatchFinalization(ex); - } - } else if (finalizationReturned) { - // A returned terminal receipt is authoritative; do not reinterpret its stored failure as - // a new attempt failure or run cleanup against it. - throw ex; - } RuntimeException operationFailure = ex instanceof PublishAttemptService.ScriptPatchTransactionException transactionFailure ? transactionFailure.causeException() @@ -227,35 +206,51 @@ public VersionDto publishScriptPatchVersion( .startsWith(PublishAttemptPendingReconciliationException.ERROR_CODE + ":"))) { throw operationFailure; } - if (!finalizationStarted - && PublicationFailureClassifier.isRetryableParticipantDependencyFailure( - operationFailure)) { + boolean retryableParticipantDependencyFailure = + PublicationFailureClassifier.isRetryableParticipantDependencyFailure(operationFailure); + boolean retryablePreDispatchParticipantFailure = + !participantGatePassed && retryableParticipantDependencyFailure; + if (retryableParticipantDependencyFailure && !retryablePreDispatchParticipantFailure) { throw new IllegalStateException( "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED: participant dependency is temporarily unavailable; retry exact publish request", operationFailure); } + String failureCode = + retryablePreDispatchParticipantFailure + ? RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + : publishFailureCode(operationFailure); + String failureMessage = + retryablePreDispatchParticipantFailure + ? retryableParticipantDependencyFailureMessage() + : publishFailureMessage(operationFailure); + ScriptPatchFinalization failure; try { - ScriptPatchFinalization failure = + failure = publishAttemptService.executeScriptPatchTransaction( - () -> - failScriptPatch( - patchBinding, - reservation, - publishFailureCode(operationFailure), - publishFailureMessage(operationFailure))); - if (failure.status() == PublishAttemptStatus.SUCCEEDED) { - notifyScriptPatchVersionUpdate(tenantId, baseVersionId, scriptPatchVersion); - return failure.versionDto(); + () -> failScriptPatch(patchBinding, reservation, failureCode, failureMessage)); + } catch (PublishAttemptService.ScriptPatchTransactionException receiptFailure) { + RuntimeException receiptOperationFailure = receiptFailure.causeException(); + receiptOperationFailure.addSuppressed(operationFailure); + throw pendingScriptPatchReconciliation(receiptOperationFailure); + } catch (RuntimeException receiptFailure) { + receiptFailure.addSuppressed(operationFailure); + throw pendingScriptPatchReconciliation(receiptFailure); + } + if (failure.status() == PublishAttemptStatus.SUCCEEDED) { + return failure.versionDto(); + } + if (failure.status() == PublishAttemptStatus.FAILED) { + if (Objects.equals(failure.failureCode(), failureCode) + && Objects.equals(failure.failureMessage(), failureMessage)) { + if (retryablePreDispatchParticipantFailure) { + throw new ScriptPatchPublishFailureException( + failure.failureCode(), failure.failureMessage(), operationFailure); + } + throw operationFailure; } - } catch (PublishAttemptService.ScriptPatchTransactionException cleanupFailure) { - RuntimeException cleanupOperationFailure = cleanupFailure.causeException(); - cleanupOperationFailure.addSuppressed(operationFailure); - throw cleanupOperationFailure; - } catch (RuntimeException cleanupFailure) { - cleanupFailure.addSuppressed(operationFailure); - throw cleanupFailure; + throw replayFailedScriptPatch(failure.failureCode(), failure.failureMessage()); } - throw operationFailure; + throw pendingScriptPatchReconciliation(operationFailure); } } @@ -289,7 +284,8 @@ private ScriptPatchReservation reserveScriptPatch( existingAttempt.getStatus(), versionMapper.toDto(publishedVersion), existingAttempt.getFailureCode(), - existingAttempt.getFailureMessage()); + existingAttempt.getFailureMessage(), + false); } if (existingAttempt.getStatus() == PublishAttemptStatus.FAILED) { return new ScriptPatchReservation( @@ -298,7 +294,8 @@ private ScriptPatchReservation reserveScriptPatch( existingAttempt.getStatus(), null, existingAttempt.getFailureCode(), - existingAttempt.getFailureMessage()); + existingAttempt.getFailureMessage(), + false); } if (existingAttempt.getStatus() != PublishAttemptStatus.PENDING) { throw new IllegalStateException("PUBLISH_ATTEMPT_INCONSISTENT: unknown attempt status"); @@ -314,7 +311,8 @@ private ScriptPatchReservation reserveScriptPatch( existingAttempt.getStatus(), versionMapper.toDto(pendingVersion), null, - null); + null, + false); } if (!versionRepository @@ -340,46 +338,7 @@ private ScriptPatchReservation reserveScriptPatch( publishAttemptService.createScriptPatchAttempt( dto, publishWorkflowId, baseVersionId, patchBinding.requestDigest()); return new ScriptPatchReservation( - publishWorkflowId, saved.getId(), PublishAttemptStatus.PENDING, dto, null, null); - } - - private ScriptPatchFinalization finalizeScriptPatch( - PublicationDigestRequestBinding patchBinding, - ScriptPatchReservation reservation, - List participantDigests, - String tenantId) { - if (gameRepository.findByTenantIdForUpdate(tenantId) == null) { - throw new IllegalArgumentException("game not found"); - } - PublishAttempt attempt = - publishAttemptService - .findByPublishWorkflowId(reservation.publishWorkflowId()) - .orElseThrow(() -> new IllegalStateException("publish attempt not found")); - if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - Version publishedVersion = requireAttemptVersion(attempt, patchBinding); - return new ScriptPatchFinalization( - attempt.getStatus(), versionMapper.toDto(publishedVersion), null, null); - } - if (attempt.getStatus() == PublishAttemptStatus.FAILED) { - return new ScriptPatchFinalization( - attempt.getStatus(), null, attempt.getFailureCode(), attempt.getFailureMessage()); - } - Version saved = requireAttemptVersion(attempt, patchBinding); - if (saved.getVersionState() != VersionLifecycleState.DRAFT) { - throw new IllegalStateException( - "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED: pending attempt does not reference a draft version"); - } - publishAttemptService.recordScriptPatchParticipantDigests( - reservation.publishWorkflowId(), participantDigests); - saved.setVersionState(VersionLifecycleState.PUBLISHED); - saved.setVersionStateEpoch(saved.getVersionStateEpoch() + 1L); - saved.setUpdatedAt(LocalDateTime.now()); - saved = versionRepository.save(saved); - recordedParticipantDigestService.recordVerifiedDigests( - tenantId, PublishType.SCRIPT_PATCH, reservation.publishWorkflowId(), participantDigests); - publishAttemptService.markScriptPatchSucceeded(reservation.publishWorkflowId()); - return new ScriptPatchFinalization( - PublishAttemptStatus.SUCCEEDED, versionMapper.toDto(saved), null, null); + publishWorkflowId, saved.getId(), PublishAttemptStatus.PENDING, dto, null, null, true); } private ScriptPatchFinalization failScriptPatch( @@ -427,7 +386,8 @@ private record ScriptPatchReservation( PublishAttemptStatus status, VersionDto versionDto, String failureCode, - String failureMessage) {} + String failureMessage, + boolean newlyCreated) {} private record ScriptPatchFinalization( PublishAttemptStatus status, @@ -492,25 +452,16 @@ private RuntimeException replayFailedScriptPatch(String failureCode, String fail } } - private ScriptPatchPublishFailureException pendingScriptPatchFinalization( + private ScriptPatchPublishFailureException pendingScriptPatchReconciliation( RuntimeException cause) { String errorCode = PublishAttemptPendingReconciliationException.ERROR_CODE; return new ScriptPatchPublishFailureException( errorCode, errorCode - + ": script-patch finalization outcome is unknown; retry the exact publish request", + + ": script-patch publication outcome is unknown; retry the exact publish request", cause); } - private void notifyScriptPatchVersionUpdate( - String tenantId, Long baseVersionId, String scriptPatchVersion) { - runSafely( - "notify script patch version update", - () -> - scriptingClient.notifyScriptVersionUpdate( - tenantId, baseVersionId, scriptPatchVersion, List.of())); - } - @Override @Transactional(readOnly = true) public VersionDto getPublishedScriptPatchVersion( @@ -882,6 +833,9 @@ private int calculateNextNumber(String tenantId) { } private String publishFailureCode(RuntimeException ex) { + if (ex instanceof ScriptPatchPublishFailureException scriptPatchFailure) { + return scriptPatchFailure.failureCode(); + } if (ex instanceof PublishGateFailureException publishGateFailureException) { return publishGateFailureException.failureCode().name(); } @@ -892,6 +846,11 @@ private String publishFailureMessage(RuntimeException ex) { return ex.getMessage() == null ? publishFailureCode(ex) : ex.getMessage(); } + private String retryableParticipantDependencyFailureMessage() { + return RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + + ": participant digest gating encountered a transient dependency failure before notification; exact retries replay this failed receipt; the retained canonical patch tuple requires owner reconciliation before any new request"; + } + private Version requireTenantVersion(String tenantId, long versionId) { return versionRepository .findByTenantIdAndId(tenantId, versionId) @@ -1078,14 +1037,6 @@ private VersionStateDto toVersionStateDto(Version version) { version.getUpdatedAt()); } - private void runSafely(String actionName, Runnable action) { - try { - action.run(); - } catch (RuntimeException ex) { - logger.warn("Failed to {}", actionName, ex); - } - } - private static void requireText(String value, String fieldName) { if (value == null || value.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: " + fieldName + " is required"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index e31f1ea2a5..c62ea5bb7d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; @@ -33,6 +34,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.entity.VersionTemplateRemapSet; +import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; @@ -122,12 +124,14 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; + @Autowired private VersionMapper versionMapper; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; @Autowired private DSLContext dsl; @Autowired private PlatformTransactionManager transactionManager; @Autowired private VersionAssetExportCandidateService exportCandidateService; @Autowired private VersionAssetPublicationService versionAssetPublicationService; @MockitoBean private AssetExportService assetExportService; + @MockitoBean private AutomationScriptingClient automationScriptingClient; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private ControlPlaneDigestService controlPlaneDigestService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @@ -584,78 +588,256 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { } @Test - void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed() { - String tenantId = "9012"; - String publishRequestId = "script-patch-finalization-failure-request"; - String scriptPatchVersion = "patch-finalization-failure"; - long baseVersionId = - createGameAndPublishedBaseVersion(tenantId, "script-patch-finalization-proof"); - Game actualGame = gameRepository.findByTenantId(tenantId); - PublicationDigestRequestBinding binding = + void publicScriptPatchWithoutManifestRetainsCanonicalDraftAndReplaysTerminalFailure() { + String tenantId = isolatedTenantId(); + long baseVersionId = createGameAndDraftBaseVersion(tenantId, "manifest-containment-game"); + String patch = "manifest-unavailable-patch"; + String requestId = "manifest-unavailable-request"; + var binding = PublicationDigestRequestBinding.patch( - tenantId, String.valueOf(baseVersionId), scriptPatchVersion, publishRequestId); - AtomicInteger participantCollectionCount = new AtomicInteger(); - + tenantId, String.valueOf(baseVersionId), patch, requestId); Mockito.when( publishGateService.collectScriptPatchParticipantDigests( - Mockito.any(VersionDto.class), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> { - participantCollectionCount.incrementAndGet(); - return List.of(); - }); - Mockito.doThrow(new IllegalStateException("recorded digest write failed")) - .when(recordedParticipantDigestService) - .recordVerifiedDigests( - Mockito.eq(tenantId), - Mockito.eq(PublishType.SCRIPT_PATCH), - Mockito.eq(binding.derivedWorkflowIdentity()), - Mockito.anyList()); + Mockito.any(VersionDto.class), + Mockito.eq(requestId), + Mockito.eq(binding.derivedWorkflowIdentity()))) + .thenReturn(List.of()); - Throwable publishFailure = + Throwable first = catchThrowable( () -> versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - scriptPatchVersion, - "finalization failure notes", - publishRequestId)); + tenantId, baseVersionId, patch, "original notes", requestId)); + assertThat(first).isInstanceOf(ScriptPatchPublishFailureException.class); + assertThat(((ScriptPatchPublishFailureException) first).failureCode()) + .isEqualTo("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + Mockito.verify(publishGateService) + .assertGatePassed(Mockito.any(VersionDto.class), Mockito.eq(List.of())); + PublishAttempt attempt = + publishAttemptRepository + .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) + .orElseThrow(); + Version candidate = + versionRepository.findByTenantIdAndId(tenantId, attempt.getVersionId()).orElseThrow(); + assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(attempt.getFailureCode()).isEqualTo("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + assertThat(attempt.getFailureMessage()).isEqualTo(first.getMessage()); + assertThat(attempt.getRequestDigest()).isEqualTo(binding.requestDigest()); + assertThat(attempt.getBaseVersionId()).isEqualTo(baseVersionId); + assertThat(attempt.getScriptPatchVersion()).isEqualTo(patch); + assertThat(attempt.getCompletedAt()).isNotNull(); + assertThat(candidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(candidate.getVersionStateEpoch()).isEqualTo(1L); + assertThat(candidate.getCanonicalTenantId()) + .isEqualTo(gameRepository.findByTenantId(tenantId).getCanonicalTenantId()); + assertThat(candidate.getCanonicalVersionId()).isNotNull(); + assertThat(candidate.getBaseVersionId()).isEqualTo(baseVersionId); + assertThat(candidate.getScriptPatchVersion()).isEqualTo(patch); + assertThat(candidate.isScriptOnly()).isTrue(); + assertThat(candidate.getNotes()).isEqualTo("original notes"); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, candidate.getId())) + .isEmpty(); + assertThat( + versionAssetArtifactRepository.findByTenantIdAndVersionId(tenantId, candidate.getId())) + .isEmpty(); + var attemptBeforeReplay = + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", attempt.getId()) + .intoMap(); + var candidateBeforeReplay = + dsl.fetchSingle("SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap(); - assertThat(publishFailure) - .isInstanceOf(IllegalStateException.class) - .hasMessage("recorded digest write failed"); - Mockito.verify(recordedParticipantDigestService) + Throwable replay = + catchThrowable( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, patch, "changed notes", requestId)); + assertThat(replay).isInstanceOf(ScriptPatchPublishFailureException.class); + assertThat(((ScriptPatchPublishFailureException) replay).failureCode()) + .isEqualTo("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + assertThat(replay).hasMessage(first.getMessage()); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + attempt.getId()) + .intoMap()) + .isEqualTo(attemptBeforeReplay); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap()) + .isEqualTo(candidateBeforeReplay); + assertThat(versionRepository.findAllByTenantIdOrderByVersionNumberAsc(tenantId)) + .extracting(Version::getId) + .containsExactly(baseVersionId, candidate.getId()); + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, patch, "fresh request", "another-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); + assertThat( + versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, patch)) + .extracting(Version::getId) + .containsExactly(candidate.getId()); + Mockito.verify(publishGateService, Mockito.times(1)) + .collectScriptPatchParticipantDigests( + Mockito.any(VersionDto.class), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(recordedParticipantDigestService, Mockito.never()) .recordVerifiedDigests( Mockito.eq(tenantId), Mockito.eq(PublishType.SCRIPT_PATCH), - Mockito.eq(binding.derivedWorkflowIdentity()), + Mockito.anyString(), Mockito.anyList()); - assertThat(participantCollectionCount).hasValue(1); + Mockito.verifyNoInteractions(automationScriptingClient); + } - PublishAttempt failedAttempt = + @Test + void realPendingScriptPatchOriginalRequiresReconciliationWithoutMutationOrDispatch() { + String tenantId = isolatedTenantId(); + long baseVersionId = createGameAndDraftBaseVersion(tenantId, "pending-patch-original-game"); + var binding = + PublicationDigestRequestBinding.patch( + tenantId, + String.valueOf(baseVersionId), + "pending-original-patch", + "pending-original-request"); + Version candidate = + createLocalScriptPatchDraft(tenantId, baseVersionId, binding.scriptPatchVersion()); + publishAttemptService.executeScriptPatchTransaction( + () -> { + publishAttemptService.createScriptPatchAttempt( + versionMapper.toDto(candidate), + binding.derivedWorkflowIdentity(), + baseVersionId, + binding.requestDigest()); + return null; + }); + PublishAttempt original = publishAttemptRepository .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) .orElseThrow(); - Version retainedCandidate = - versionRepository.findByTenantIdAndId(tenantId, failedAttempt.getVersionId()).orElseThrow(); - assertThat(failedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); - assertThat(failedAttempt.getFailureCode()).isEqualTo("PUBLISH_FAILED"); - assertThat(failedAttempt.getFailureMessage()).isEqualTo("recorded digest write failed"); - assertThat(failedAttempt.getCompletedAt()).isNotNull(); - assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); - assertThat(retainedCandidate.getVersionStateEpoch()).isEqualTo(1L); - assertThat(retainedCandidate.getBaseVersionId()).isEqualTo(baseVersionId); - assertThat(retainedCandidate.getScriptPatchVersion()).isEqualTo(scriptPatchVersion); - assertThat(retainedCandidate.getCanonicalVersionId()).isNotNull(); - assertThat(retainedCandidate.getCanonicalTenantId()) - .isEqualTo(actualGame.getCanonicalTenantId()); - assertThat(retainedCandidate.isScriptOnly()).isTrue(); + var originalAttempt = + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", original.getId()) + .intoMap(); + var originalCandidate = + dsl.fetchSingle("SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap(); + + for (int retry = 0; retry < 2; retry++) { + Throwable failure = + catchThrowable( + () -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + binding.scriptPatchVersion(), + "changed notes", + binding.publishRequestId())); + assertThat(failure).isInstanceOf(ScriptPatchPublishFailureException.class); + assertThat(((ScriptPatchPublishFailureException) failure).failureCode()) + .isEqualTo(PublishAttemptPendingReconciliationException.ERROR_CODE); + assertThat(failure.getCause()).hasMessageContaining("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + } assertThat( - versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( - tenantId, baseVersionId, scriptPatchVersion)) + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + original.getId()) + .intoMap()) + .isEqualTo(originalAttempt); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap()) + .isEqualTo(originalCandidate); + assertThat( + publishAttemptRepository + .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) + .orElseThrow() + .getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); + assertThat(versionRepository.findAllByTenantIdOrderByVersionNumberAsc(tenantId)) .extracting(Version::getId) - .containsExactly(retainedCandidate.getId()); + .containsExactly(baseVersionId, candidate.getId()); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, candidate.getId())) + .isEmpty(); + Mockito.verifyNoInteractions(publishGateService, automationScriptingClient); + } + + @Test + void scriptPatchOwnerTransactionRollsBackDraftEditAndAttemptFailureTogether() { + String tenantId = isolatedTenantId(); + long baseVersionId = createGameAndDraftBaseVersion(tenantId, "script-owner-rollback-game"); + var binding = + PublicationDigestRequestBinding.patch( + tenantId, + String.valueOf(baseVersionId), + "owner-rollback-patch", + "owner-rollback-request"); + Version candidate = + createLocalScriptPatchDraft(tenantId, baseVersionId, binding.scriptPatchVersion()); + publishAttemptService.executeScriptPatchTransaction( + () -> { + publishAttemptService.createScriptPatchAttempt( + versionMapper.toDto(candidate), + binding.derivedWorkflowIdentity(), + baseVersionId, + binding.requestDigest()); + return null; + }); + PublishAttempt original = + publishAttemptRepository + .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) + .orElseThrow(); + var originalAttempt = + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", original.getId()) + .intoMap(); + var originalCandidate = + dsl.fetchSingle("SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap(); + + assertThatThrownBy( + () -> + publishAttemptService.executeScriptPatchTransaction( + () -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + Version locked = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, candidate.getId()) + .orElseThrow(); + locked.setNotes("rolled back owner edit"); + versionRepository.save(locked); + publishAttemptService.markScriptPatchFailed( + binding.derivedWorkflowIdentity(), + "OWNER_ROLLBACK_PROBE", + "rolled back failure"); + throw new IllegalStateException("forced script owner transaction failure"); + })) + .isInstanceOf(PublishAttemptService.ScriptPatchTransactionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + original.getId()) + .intoMap()) + .isEqualTo(originalAttempt); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) + .intoMap()) + .isEqualTo(originalCandidate); + Mockito.verifyNoInteractions(publishGateService, automationScriptingClient); } @Test @@ -1359,6 +1541,33 @@ private static ExportedAssetManifest exportedManifest() { 1))); } + private long createGameAndDraftBaseVersion(String tenantId, String gameName) { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName(gameName); + gameRepository.save(game); + Version base = new Version(); + base.setTenantId(tenantId); + base.setVersionNumber(1); + base.setVersionState(VersionLifecycleState.DRAFT); + base.setVersionStateEpoch(1L); + base.setNotes("local draft base without publication authority"); + return versionRepository.save(base).getId(); + } + + private Version createLocalScriptPatchDraft(String tenantId, long baseVersionId, String patch) { + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(2); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setBaseVersionId(baseVersionId); + candidate.setScriptPatchVersion(patch); + candidate.setScriptOnly(true); + candidate.setNotes("original pending draft"); + return versionRepository.save(candidate); + } + private long createGameAndPublishedBaseVersion(String tenantId, String gameName) { Game game = new Game(); game.setTenantId(tenantId); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java index 1b3afe49c0..29077384a7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java @@ -1,7 +1,7 @@ package net.firedevops.firemud.gamedesign.client; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -14,6 +14,7 @@ import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse; import net.firedevops.firemud.automationscripting.v1.NotifyScriptVersionUpdateRequest; +import net.firedevops.firemud.automationscripting.v1.NotifyScriptVersionUpdateResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -93,6 +94,70 @@ void patchDigestReadCarriesBindingAndRejectsMismatchedTenant() throws Exception assertThat(request.getRequestDigest()).isEqualTo(binding.requestDigest()); } + @Test + void notificationWithoutAcceptedReadinessFailsClosed() throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub stub = + mock(AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub.class); + when(stub.notifyScriptVersionUpdate(any(NotifyScriptVersionUpdateRequest.class))) + .thenReturn(NotifyScriptVersionUpdateResponse.newBuilder().setSuccess(false).build()); + TestAutomationScriptingClient client = + new TestAutomationScriptingClient( + endpoints, + grpc, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + stub); + client.initialize(); + + assertThatThrownBy( + () -> + client.notifyScriptVersionUpdate( + "tenant-1", 7L, "patch-7", java.util.List.of("script-a"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SCRIPT_PATCH_NOTIFICATION_REJECTED"); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(NotifyScriptVersionUpdateRequest.class); + verify(stub).notifyScriptVersionUpdate(requestCaptor.capture()); + NotifyScriptVersionUpdateRequest request = requestCaptor.getValue(); + assertThat(request.getTenantId()).isEqualTo("tenant-1"); + assertThat(request.getBaseVersionId()).isEqualTo(7L); + assertThat(request.getScriptPatchVersion()).isEqualTo("patch-7"); + assertThat(request.getAffectedScriptsList()).containsExactly("script-a"); + } + + @Test + void identifiableEmptyNotificationReachesReadinessOwnerAndSurfacesRejection() throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub stub = + mock(AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub.class); + when(stub.notifyScriptVersionUpdate(any(NotifyScriptVersionUpdateRequest.class))) + .thenReturn(NotifyScriptVersionUpdateResponse.newBuilder().setSuccess(false).build()); + TestAutomationScriptingClient client = + new TestAutomationScriptingClient( + endpoints, + grpc, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + stub); + client.initialize(); + + assertThatThrownBy( + () -> client.notifyScriptVersionUpdate("tenant-1", 7L, "patch-7", java.util.List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SCRIPT_PATCH_NOTIFICATION_REJECTED"); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(NotifyScriptVersionUpdateRequest.class); + verify(stub).notifyScriptVersionUpdate(requestCaptor.capture()); + NotifyScriptVersionUpdateRequest request = requestCaptor.getValue(); + assertThat(request.getTenantId()).isEqualTo("tenant-1"); + assertThat(request.getBaseVersionId()).isEqualTo(7L); + assertThat(request.getScriptPatchVersion()).isEqualTo("patch-7"); + assertThat(request.getAffectedScriptsList()).isEmpty(); + } + @Test void fullDigestReadRejectsLegacyResponseWithoutTypedScope() throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); @@ -164,6 +229,8 @@ void scriptPatchNotificationCarriesExactBaseVersion() throws Exception { grpc.setPlaintext(true); AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub stub = mock(AutomationScriptingServiceGrpc.AutomationScriptingServiceBlockingStub.class); + when(stub.notifyScriptVersionUpdate(any(NotifyScriptVersionUpdateRequest.class))) + .thenReturn(NotifyScriptVersionUpdateResponse.newBuilder().setSuccess(true).build()); TestAutomationScriptingClient client = new TestAutomationScriptingClient( endpoints, @@ -202,12 +269,15 @@ void scriptPatchNotificationRejectsMissingOrNonpositiveBaseBeforeCallingAutomati client.initialize(); for (Long baseVersionId : java.util.Arrays.asList(null, 0L, -1L)) { - assertThatIllegalArgumentException() - .isThrownBy( + assertThatThrownBy( () -> client.notifyScriptVersionUpdate( - "tenant-1", baseVersionId, "patch-7", java.util.List.of())); + "tenant-1", baseVersionId, "patch-7", java.util.List.of("script-a"))) + .isInstanceOf(IllegalArgumentException.class); } + assertThatThrownBy(() -> client.notifyScriptVersionUpdate("tenant-1", 7L, "patch-7", null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("affectedScripts"); verify(stub, never()).notifyScriptVersionUpdate(any(NotifyScriptVersionUpdateRequest.class)); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 2d81d48ebd..a35bf4f9e0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -655,6 +655,35 @@ void publishScriptPatchVersionMapsReplayedFailureCodeAndMessage() throws Excepti assertEquals("stored identity cannot be replayed", ref.get().getError().getMessage()); } + @Test + void publishScriptPatchVersionMapsManifestUnavailableToStableApplicationError() throws Exception { + Mockito.when( + versionService.publishScriptPatchVersion( + "tenant-1", 7L, "patch-1", "notes", "publish-request-1")) + .thenThrow( + new ScriptPatchPublishFailureException( + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE", + "owner-verified affected-script manifest is unavailable")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishScriptPatchVersion( + PublishScriptPatchVersionRequest.newBuilder() + .setTenantId("tenant-1") + .setBaseVersionId(7L) + .setScriptPatchVersion("patch-1") + .setNotes("notes") + .setPublishRequestId("publish-request-1") + .build(), + observerFor(ref)); + } + + assertEquals("SCRIPT_PATCH_MANIFEST_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals( + "owner-verified affected-script manifest is unavailable", + ref.get().getError().getMessage()); + } + @Test void publishVersionMapsPendingReconciliationToStableApplicationError() throws Exception { Mockito.when(versionService.publishVersion(selectedIntent("request-1"))) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index aded1707ee..06813808f5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.never; @@ -761,6 +762,52 @@ void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { thrown.getMessage()); } + @Test + void retainedCommittedPatchCannotReplayOrReadBackWithoutOwnerReadinessEvidence() { + var request = request("cp-retained-patch", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + var stored = descriptorFor(request, 7L, 11L); + var patched = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + stored.getLaunchDescriptorId(), + 7L, + true, + "retained-patch", + "{}", + "genrev-1", + 17L, + 11L, + PUBLISHED_RELEASE_BUNDLE_REF, + false, + null); + stored.setScriptPatchVersion("retained-patch"); + stored.setResultDigest(patched.resultDigest()); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException replay = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + assertTrue(replay.getMessage().startsWith("SCRIPT_PATCH_NOT_READY:")); + IllegalArgumentException read = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + request.controlPlaneRequestId(), + request.requestDigest(), + patched.resultDigest())); + assertTrue(read.getMessage().startsWith("SCRIPT_PATCH_NOT_READY:")); + assertEquals("retained-patch", stored.getScriptPatchVersion()); + assertEquals(patched.resultDigest(), stored.getResultDigest()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + @Test void storedDescriptorReplayRejectsChangedAuthoredSourceTuple() { AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered-source", 9L); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 721d120931..8ddccebd1c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -21,6 +21,9 @@ import java.util.function.Supplier; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.client.WorldManagementClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; @@ -37,6 +40,7 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PluginVersionStatusEventRepository; import net.firedevops.firemud.gamedesign.repository.PublishedPluginVersionRepository; @@ -69,6 +73,8 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE = + "PARTICIPANT_DEPENDENCY_UNAVAILABLE_RETRYABLE"; private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); @@ -131,7 +137,6 @@ void setup() throws Exception { publishedPluginVersionRepository, pluginVersionStatusEventRepository, mapper, - scriptingClient, publishAttemptService, publishGateService, controlPlaneDigestService, @@ -277,7 +282,7 @@ void legacyFullVersionRequestOnlyDelegatesToRetainedTerminalReplay() throws Exce } @Test - void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception { + void missingManifestFailsBeforeNotificationAndRetainsCanonicalDraft() throws Exception { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -301,53 +306,36 @@ void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception savedDraft.setBaseVersionId(3L); savedDraft.setScriptOnly(true); savedDraft.setUpdatedAt(java.time.LocalDateTime.now()); - Version savedPublished = new Version(); - savedPublished.setId(11L); - savedPublished.setTenantId("tenant-1"); - savedPublished.setVersionNumber(8); - savedPublished.setScriptPatchVersion("patch-2"); - savedPublished.setNotes("notes"); - savedPublished.setVersionState(VersionLifecycleState.PUBLISHED); - savedPublished.setVersionStateEpoch(2L); - savedPublished.setBaseVersionId(3L); - savedPublished.setScriptOnly(true); - savedPublished.setUpdatedAt(java.time.LocalDateTime.now()); PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt pendingAttempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + PublishAttempt failedAttempt = + scriptPatchAttempt(binding, PublishAttemptStatus.FAILED, 11L, 8, 3L); + failedAttempt.setFailureCode("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + failedAttempt.setFailureMessage( + "SCRIPT_PATCH_MANIFEST_UNAVAILABLE: the reserved patch has no owner-verified affected-script manifest"); when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) - .thenReturn(Optional.empty(), Optional.of(pendingAttempt)); + .thenReturn(Optional.empty(), Optional.of(pendingAttempt), Optional.of(failedAttempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) .thenReturn(Optional.of(savedDraft)); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft, savedPublished); + when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn( - List.of( - new PublishParticipantDigestDto( - "AUTOMATION_SCRIPTING", - "patch-2", - "script-patch:patch-2", - "digest-1", - 1, - null, - null), - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - "patch-2", - "script-patch:patch-2", - "digest-2", - 1, - null, - null))); + .thenReturn(List.of()); - VersionDto dto = - service.publishScriptPatchVersion("tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID); + ScriptPatchPublishFailureException firstFailure = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - verify(versionRepository, times(2)).save(any(Version.class)); + assertEquals("SCRIPT_PATCH_MANIFEST_UNAVAILABLE", firstFailure.failureCode()); + org.mockito.Mockito.verifyNoInteractions(scriptingClient); + verify(versionRepository, times(1)).save(any(Version.class)); verify(publishAttemptService) .createScriptPatchAttempt( any(VersionDto.class), @@ -358,12 +346,165 @@ void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception PublicationDigestRequestBinding.patch( "tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID) .requestDigest())); - verify(scriptingClient) - .notifyScriptVersionUpdate("tenant-1", 3L, "patch-2", java.util.List.of()); - verify(recordedParticipantDigestService) + verify(publishAttemptService) + .markScriptPatchFailed( + org.mockito.ArgumentMatchers.eq(binding.derivedWorkflowIdentity()), + org.mockito.ArgumentMatchers.eq("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"), + org.mockito.ArgumentMatchers.contains("owner-verified affected-script manifest")); + verify(versionRepository, org.mockito.Mockito.never()).delete(savedDraft); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchSucceeded(any(String.class)); + ScriptPatchPublishFailureException replay = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); + + assertEquals(firstFailure.failureCode(), replay.failureCode()); + assertEquals(firstFailure.getMessage(), replay.getMessage()); + verify(publishAttemptService, times(1)) + .createScriptPatchAttempt(any(), any(String.class), any(Long.class), any(String.class)); + verify(publishGateService, times(1)) + .collectScriptPatchParticipantDigests(any(), any(String.class), any(String.class)); + } + + @Test + void unsupportedAutomationDigestScopeBlocksScriptPatchBeforeNotification() { + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + + Version latest = new Version(); + latest.setId(9L); + latest.setTenantId("tenant-1"); + latest.setVersionNumber(7); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.of(latest)); + + Version savedDraft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); + when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + PublishAttempt pendingAttempt = + scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.empty(), Optional.of(pendingAttempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); + when(scriptingClient.getDraftDesignDigestForScriptPatch( + any(PublicationDigestRequestBinding.class))) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "patch-2", + 3L, + null, + null, + null, + "UNSUPPORTED_SCOPE", + "script-patch digest scope is unsupported")); + when(controlPlaneDigestService.getDigestForScriptPatch(any(VersionDto.class))) + .thenReturn( + new DesignControlPlaneDigestDto( + "tenant-1", "patch-2", "commit-1", "control-plane-digest", 1)); + + PublishGateServiceImpl realPublishGate = + new PublishGateServiceImpl( + controlPlaneDigestService, + org.mockito.Mockito.mock(WorldManagementClient.class), + org.mockito.Mockito.mock(EntityManagementClient.class), + org.mockito.Mockito.mock(GameLogicClient.class), + scriptingClient, + org.mockito.Mockito.mock(SelectedDraftGameLogicReceiptRepository.class)); + VersionServiceImpl composedService = serviceWithPublishGate(realPublishGate); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> + composedService.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, thrown.failureCode()); + assertEquals("UNSUPPORTED_SCOPE", thrown.participantFailureCode()); + String workflowId = "publish-script-patch:tenant-1:publish-request:" + PUBLISH_REQUEST_ID; + ArgumentCaptor bindingCaptor = + ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(scriptingClient).getDraftDesignDigestForScriptPatch(bindingCaptor.capture()); + PublicationDigestRequestBinding observedBinding = bindingCaptor.getValue(); + assertEquals(binding.tenantId(), observedBinding.tenantId()); + assertEquals(binding.scopeKind(), observedBinding.scopeKind()); + assertEquals(binding.baseVersionId(), observedBinding.baseVersionId()); + assertEquals(binding.scriptPatchVersion(), observedBinding.scriptPatchVersion()); + assertEquals(binding.publishRequestId(), observedBinding.publishRequestId()); + assertEquals(binding.derivedWorkflowIdentity(), observedBinding.derivedWorkflowIdentity()); + assertEquals(binding.requestDigest(), observedBinding.requestDigest()); + verify(scriptingClient, org.mockito.Mockito.never()) + .notifyScriptVersionUpdate("tenant-1", 3L, "patch-2", List.of()); + verify(publishAttemptService) + .markScriptPatchFailed( + org.mockito.ArgumentMatchers.eq(workflowId), + org.mockito.ArgumentMatchers.eq(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE.name()), + org.mockito.ArgumentMatchers.contains("script-patch digest scope is unsupported")); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchSucceeded(any(String.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .recordScriptPatchParticipantDigests(any(String.class), any(List.class)); + verify(versionRepository, times(1)).save(any(Version.class)); + verify(versionRepository, org.mockito.Mockito.never()).delete(savedDraft); + verify(recordedParticipantDigestService, org.mockito.Mockito.never()) .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); } + @Test + void concurrentDifferentFailedReceiptOverridesCurrentParticipantFailure() { + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + Version latest = new Version(); + latest.setId(9L); + latest.setTenantId("tenant-1"); + latest.setVersionNumber(7); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.of(latest)); + when(versionRepository.save(any(Version.class))) + .thenReturn(scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes")); + + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + PublishAttempt concurrentFailure = + scriptPatchAttempt(binding, PublishAttemptStatus.FAILED, 11L, 8, 3L); + concurrentFailure.setFailureCode("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); + concurrentFailure.setFailureMessage("stored manifest failure"); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.empty(), Optional.of(concurrentFailure)); + when(publishGateService.collectScriptPatchParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenThrow( + new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, + "participant observation failed", + "UNSUPPORTED_SCOPE")); + + ScriptPatchPublishFailureException thrown = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals("SCRIPT_PATCH_MANIFEST_UNAVAILABLE", thrown.failureCode()); + assertEquals("stored manifest failure", thrown.getMessage()); + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + } + @Test void sameStableScriptPatchIdReplaysSucceededAttemptWithoutAllocatingVersion() { Game game = new Game(); @@ -393,11 +534,10 @@ void sameStableScriptPatchIdReplaysSucceededAttemptWithoutAllocatingVersion() { .createScriptPatchAttempt(any(), any(), any(), any()); verify(publishGateService, org.mockito.Mockito.never()) .collectScriptPatchParticipantDigests(any(), any(), any()); - verify(scriptingClient).notifyScriptVersionUpdate("tenant-1", 3L, "patch-2", List.of()); } @Test - void concurrentScriptPatchSuccessNotifiesAfterParticipantFailure() { + void pendingScriptPatchRetryReplaysConcurrentSuccessWithoutDispatch() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -413,21 +553,27 @@ void concurrentScriptPatchSuccessNotifiesAfterParticipantFailure() { .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) .thenReturn(Optional.of(draft), Optional.of(published)); - doAnswer( - invocation -> { - attempt.setStatus(PublishAttemptStatus.SUCCEEDED); - throw new IllegalStateException("participant read failed after concurrent success"); - }) - .when(publishGateService) - .collectScriptPatchParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class)); + ScriptPatchPublishFailureException pending = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals(PublishAttemptPendingReconciliationException.ERROR_CODE, pending.failureCode()); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); VersionDto result = service.publishScriptPatchVersion("tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID); assertEquals(11L, result.id()); assertEquals(VersionLifecycleState.PUBLISHED, result.versionState()); - verify(scriptingClient).notifyScriptVersionUpdate("tenant-1", 3L, "patch-2", List.of()); + verify(publishGateService, org.mockito.Mockito.never()) + .collectScriptPatchParticipantDigests(any(), any(), any()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); } @Test @@ -455,6 +601,8 @@ void sameStableScriptPatchIdRejectsSucceededDraftWithoutAllocatingVersion() { when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); assertThrows( IllegalStateException.class, @@ -488,13 +636,14 @@ private void assertSucceededScriptPatchReplayForLifecycle(VersionLifecycleState assertEquals(11L, replay.id()); assertEquals(lifecycleState, replay.versionState()); + org.mockito.Mockito.verifyNoInteractions(scriptingClient); verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); verify(publishAttemptService, org.mockito.Mockito.never()) .createScriptPatchAttempt(any(), any(), any(), any()); } @Test - void sameStableScriptPatchIdResumesExactPendingDraftWithoutCreatingAttempt() { + void sameStableScriptPatchIdKeepsPriorPendingAttemptForReconciliation() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -504,25 +653,30 @@ void sameStableScriptPatchIdResumesExactPendingDraftWithoutCreatingAttempt() { PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "first notes"); - Version published = - scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.PUBLISHED, "first notes"); when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); - when(versionRepository.save(any(Version.class))).thenReturn(published); - when(publishGateService.collectScriptPatchParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(List.of()); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); - VersionDto replay = - service.publishScriptPatchVersion( - "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID); + ScriptPatchPublishFailureException thrown = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); - assertEquals(11L, replay.id()); - assertEquals(VersionLifecycleState.PUBLISHED, replay.versionState()); + assertEquals(PublishAttemptPendingReconciliationException.ERROR_CODE, thrown.failureCode()); + assertTrue(thrown.getCause().getMessage().contains("SCRIPT_PATCH_MANIFEST_UNAVAILABLE")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); verify(publishAttemptService, org.mockito.Mockito.never()) .createScriptPatchAttempt(any(), any(), any(), any()); - verify(publishAttemptService).markScriptPatchSucceeded(binding.derivedWorkflowIdentity()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .collectScriptPatchParticipantDigests(any(), any(String.class), any(String.class)); } @Test @@ -541,6 +695,8 @@ void failedScriptPatchRecordsStableAttemptAndRetainsDraft() { Version savedDraft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt pendingAttempt = @@ -549,8 +705,6 @@ void failedScriptPatchRecordsStableAttemptAndRetainsDraft() { .thenReturn(Optional.empty(), Optional.of(pendingAttempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) .thenReturn(Optional.of(savedDraft)); - when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) - .thenReturn(Optional.of(savedDraft)); when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenThrow( @@ -593,45 +747,69 @@ void failedScriptPatchRecordsStableAttemptAndRetainsDraft() { @EnumSource( value = Status.Code.class, names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) - void transientParticipantReadLeavesScriptPatchPending(Status.Code statusCode) { + void transientPreDispatchFailureRetainsCanonicalTupleAndReplaysFailure(Status.Code statusCode) { Game game = new Game(); - game.setId(1L); game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); - PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); + PublishAttempt pending = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + PublishAttempt failed = scriptPatchAttempt(binding, PublishAttemptStatus.FAILED, 11L, 8, 3L); + String failureMessage = + RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + + ": participant digest gating encountered a transient dependency failure before notification; exact retries replay this failed receipt; the retained canonical patch tuple requires owner reconciliation before any new request"; + failed.setFailureCode(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE); + failed.setFailureMessage(failureMessage); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.empty()); + when(versionRepository.save(any(Version.class))).thenReturn(draft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); - when(publishGateService.collectScriptPatchParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(Optional.empty(), Optional.of(pending), Optional.of(failed)); + when(publishGateService.collectScriptPatchParticipantDigests(any(), any(), any())) .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); - IllegalStateException thrown = + ScriptPatchPublishFailureException first = assertThrows( - IllegalStateException.class, + ScriptPatchPublishFailureException.class, () -> service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); - - assertTrue(thrown.getMessage().contains("PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); + assertEquals(failureMessage, first.getMessage()); + verify(publishAttemptService) + .markScriptPatchFailed( + binding.derivedWorkflowIdentity(), + RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, + failureMessage); + ScriptPatchPublishFailureException replay = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "changed notes", PUBLISH_REQUEST_ID)); + assertEquals(first.failureCode(), replay.failureCode()); + assertEquals(first.getMessage(), replay.getMessage()); + when(versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + "tenant-1", 3L, "patch-2")) + .thenReturn(List.of(draft)); + IllegalArgumentException conflict = + assertThrows( + IllegalArgumentException.class, + () -> + service.publishScriptPatchVersion("tenant-1", 3L, "patch-2", "new", "new-request")); + assertTrue(conflict.getMessage().startsWith("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT:")); assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); - verify(publishAttemptService, org.mockito.Mockito.never()) - .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); - verify(publishAttemptService, org.mockito.Mockito.never()) - .markScriptPatchSucceeded(any(String.class)); + verify(versionRepository).save(any(Version.class)); verify(scriptingClient, org.mockito.Mockito.never()) - .notifyScriptVersionUpdate( - any(String.class), any(Long.class), any(String.class), any(List.class)); + .notifyScriptVersionUpdate(any(), any(), any(), any()); } @Test - void pendingReconciliationFailureDoesNotFailOrDeleteScriptPatchAttempt() { + void pendingNonDraftCandidateRemainsHeldForReconciliation() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -640,16 +818,10 @@ void pendingReconciliationFailureDoesNotFailOrDeleteScriptPatchAttempt() { PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); - Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); - Version concurrentlyPublished = - scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.PUBLISHED, "notes"); + Version published = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.PUBLISHED, "notes"); when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) - .thenReturn(Optional.of(draft), Optional.of(concurrentlyPublished)); - when(publishGateService.collectScriptPatchParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(List.of()); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(published)); IllegalStateException thrown = assertThrows( @@ -660,17 +832,16 @@ void pendingReconciliationFailureDoesNotFailOrDeleteScriptPatchAttempt() { assertTrue(thrown.getMessage().startsWith("PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED:")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); + assertEquals(VersionLifecycleState.PUBLISHED, published.getVersionState()); verify(publishAttemptService, org.mockito.Mockito.never()) .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); - verify(scriptingClient, org.mockito.Mockito.never()) - .notifyScriptVersionUpdate( - any(String.class), any(Long.class), any(String.class), any(List.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .collectScriptPatchParticipantDigests(any(), any(String.class), any(String.class)); } @Test - void ambiguousFinalizationDoesNotNotifyScriptVersionUpdate() { + void ambiguousManifestFailureReceiptTransactionRemainsPendingForExactRetry() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -681,7 +852,12 @@ void ambiguousFinalizationDoesNotNotifyScriptVersionUpdate() { PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) - .thenReturn(Optional.of(attempt)); + .thenReturn(Optional.empty(), Optional.of(attempt)); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.empty()); + when(versionRepository.save(any(Version.class))).thenReturn(draft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) @@ -690,11 +866,10 @@ void ambiguousFinalizationDoesNotNotifyScriptVersionUpdate() { AtomicInteger transactionCalls = new AtomicInteger(); doAnswer( invocation -> { - Object result = ((Supplier) invocation.getArgument(0)).get(); if (transactionCalls.incrementAndGet() == 2) { throw new IllegalStateException("transaction completion outcome is ambiguous"); } - return result; + return ((Supplier) invocation.getArgument(0)).get(); }) .when(publishAttemptService) .executeScriptPatchTransaction(any()); @@ -713,16 +888,128 @@ void ambiguousFinalizationDoesNotNotifyScriptVersionUpdate() { .startsWith(PublishAttemptPendingReconciliationException.ERROR_CODE + ":")); assertEquals("transaction completion outcome is ambiguous", thrown.getCause().getMessage()); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(scriptingClient, org.mockito.Mockito.never()) - .notifyScriptVersionUpdate( - any(String.class), any(Long.class), any(String.class), any(List.class)); verify(publishAttemptService, org.mockito.Mockito.never()) .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + + ScriptPatchPublishFailureException retryFailure = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals( + PublishAttemptPendingReconciliationException.ERROR_CODE, retryFailure.failureCode()); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + } + + @Test + void manifestUnavailableAfterPassingParticipantGatesFailsAndRetainsCandidate() { + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.empty()); + when(versionRepository.save(any(Version.class))).thenReturn(draft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.empty(), Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(publishGateService.collectScriptPatchParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(List.of()); + ScriptPatchPublishFailureException thrown = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals("SCRIPT_PATCH_MANIFEST_UNAVAILABLE", thrown.failureCode()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchSucceeded(any(String.class)); + verify(publishAttemptService) + .markScriptPatchFailed( + org.mockito.ArgumentMatchers.eq(binding.derivedWorkflowIdentity()), + org.mockito.ArgumentMatchers.eq("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"), + org.mockito.ArgumentMatchers.contains("owner-verified affected-script manifest")); + verify(versionRepository, org.mockito.Mockito.never()).delete(draft); + } + + @Test + void legacyPendingAttemptWithPossibleDispatchRemainsHeldForReconciliation() { + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertTrue(thrown.getMessage().contains("PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED")); + assertTrue(thrown.getCause().getMessage().contains("SCRIPT_PATCH_MANIFEST_UNAVAILABLE")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + } + + @Test + void pendingAttemptRemainsHeldWithoutRedispatchOrCleanup() { + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); + ScriptPatchPublishFailureException thrown = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); + + assertEquals(PublishAttemptPendingReconciliationException.ERROR_CODE, thrown.failureCode()); + assertTrue(thrown.getCause().getMessage().contains("SCRIPT_PATCH_MANIFEST_UNAVAILABLE")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); } @Test - void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() { + void manifestFailureReceiptWriteErrorRetainsPendingForExactRetry() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -739,6 +1026,8 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() Version draftAfterRollback = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); when(versionRepository.save(any(Version.class))).thenReturn(draft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) .thenReturn(Optional.of(draftAfterRollback)); @@ -751,46 +1040,36 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(List.of()); - doThrow(new IllegalStateException("recorded digest write failed")) - .when(recordedParticipantDigestService) - .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); + doThrow(new IllegalStateException("failure receipt write failed")) + .when(publishAttemptService) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); - IllegalStateException firstFailure = + ScriptPatchPublishFailureException firstFailure = assertThrows( - IllegalStateException.class, + ScriptPatchPublishFailureException.class, () -> service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); - - assertEquals("recorded digest write failed", firstFailure.getMessage()); - String workflowId = binding.derivedWorkflowIdentity(); + assertEquals( + PublishAttemptPendingReconciliationException.ERROR_CODE, firstFailure.failureCode()); + assertEquals("failure receipt write failed", firstFailure.getCause().getMessage()); assertEquals(VersionLifecycleState.DRAFT, draftAfterRollback.getVersionState()); - assertEquals(3L, draftAfterRollback.getBaseVersionId()); - assertEquals("patch-2", draftAfterRollback.getScriptPatchVersion()); - verify(versionRepository, org.mockito.Mockito.never()).delete(draftAfterRollback); - verify(scriptingClient, org.mockito.Mockito.never()) - .notifyScriptVersionUpdate( - any(String.class), any(Long.class), any(String.class), any(List.class)); - verify(publishAttemptService) - .markScriptPatchFailed( - org.mockito.ArgumentMatchers.eq(workflowId), - org.mockito.ArgumentMatchers.eq("PUBLISH_FAILED"), - org.mockito.ArgumentMatchers.eq("recorded digest write failed")); - - pendingAttempt.setStatus(PublishAttemptStatus.FAILED); - pendingAttempt.setFailureCode("PUBLISH_FAILED"); - pendingAttempt.setFailureMessage("recorded digest write failed"); - when(publishAttemptService.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(pendingAttempt)); - - IllegalStateException retryFailure = + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + ScriptPatchPublishFailureException replay = assertThrows( - IllegalStateException.class, + ScriptPatchPublishFailureException.class, () -> service.publishScriptPatchVersion( - "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); - assertEquals("recorded digest write failed", retryFailure.getMessage()); - verify(versionRepository, times(2)).save(any(Version.class)); + "tenant-1", 3L, "patch-2", "changed notes", PUBLISH_REQUEST_ID)); + assertEquals(PublishAttemptPendingReconciliationException.ERROR_CODE, replay.failureCode()); + verify(versionRepository).save(any(Version.class)); + verify(publishAttemptService) + .markScriptPatchFailed( + org.mockito.ArgumentMatchers.eq(binding.derivedWorkflowIdentity()), + org.mockito.ArgumentMatchers.eq("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"), + org.mockito.ArgumentMatchers.contains("owner-verified affected-script manifest")); + verify(scriptingClient, org.mockito.Mockito.never()) + .notifyScriptVersionUpdate(any(), any(), any(), any()); } @Test @@ -932,6 +1211,25 @@ void retainedDraftScriptPatchTupleRejectsFreshPublicationWithoutAllocation() { .createScriptPatchAttempt(any(), any(), any(), any()); } + private VersionServiceImpl serviceWithPublishGate(PublishGateService gate) { + return new VersionServiceImpl( + versionRepository, + gameRepository, + publishedPluginVersionRepository, + pluginVersionStatusEventRepository, + Mappers.getMapper(VersionMapper.class), + publishAttemptService, + gate, + controlPlaneDigestService, + versionAssetArtifactService, + publishedReleaseBundleService, + recordedParticipantDigestService, + pluginBundleIntakeService, + pluginBundleStorageService, + publishCommandService, + Optional.empty()); + } + private PublishAttempt scriptPatchAttempt( PublicationDigestRequestBinding binding, PublishAttemptStatus status, @@ -991,7 +1289,6 @@ void publishVersionDoesNotStartTemporalWorkflowWithoutOwnerFreeze() { publishedPluginVersionRepository, pluginVersionStatusEventRepository, Mappers.getMapper(VersionMapper.class), - scriptingClient, publishAttemptService, publishGateService, controlPlaneDigestService, From 4db80f847ccd453b1b14a1e70180b18b83d3021b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:57:33 +1300 Subject: [PATCH 02/11] Record carried publication containment image proof --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e90ab41f3a..da402b2e10 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 @@ -516,4 +516,4 @@ No competing current authority is recorded for settings, versioned release bundl | Logging & Admin | Operator-facing compatibility and publication control-plane ingress | Canonical Game Design and runtime projections | | Temporal | Durable publish/readiness workflow execution where long-lived waiting is required | Workflow identity/status surfaced through canonical reads | -R1420 local publication-containment proof passes 178 selected Game Design cases: 156 unit cases and 22 actual PostgreSQL/application cases, alongside 50 Automation units in the combined gate. The real patch owner records a manifest-unavailable terminal failure while retaining its canonical DRAFT tuple; exact retry preserves complete attempt/candidate rows and `xmin`, a genuine pre-existing PENDING original remains unchanged without redispatch, and the direct owner transaction rolls back its Draft/attempt writes together. Launch-descriptor SQL and current full-version offline transaction controls also pass. Participant gates are controlled collaborators, not genuine publication or manifest authority. Enabled affected static analysis, full formatting, both service packages and documentation checks pass; fresh source-built runtime proof remains pending on the carried parent. Existing full-publication authorization refusal, production manifest/readiness, Account/World source authority, recovery and activation holds remain. +R1420 local publication-containment proof passes 178 selected Game Design cases: 156 unit cases and 22 actual PostgreSQL/application cases, alongside 50 Automation units in the combined gate. The real patch owner records a manifest-unavailable terminal failure while retaining its canonical DRAFT tuple; exact retry preserves complete attempt/candidate rows and `xmin`, a genuine pre-existing PENDING original remains unchanged without redispatch, and the direct owner transaction rolls back its Draft/attempt writes together. Launch-descriptor SQL and current full-version offline transaction controls also pass. Participant gates are controlled collaborators, not genuine publication or manifest authority. Enabled affected static analysis, full formatting, both service packages and documentation checks pass; fresh canonical image-lane held smoke builds all eleven applications from carried source `eaee2ed9af91c2a6ad217df0b00d1bea16dcbb5f` and passes direct backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial. Authenticated run-owned teardown and independent exact-project queries find no containers, networks or volumes. Successful public admission and production publication/activation remain unproved. Existing full-publication authorization refusal, production manifest/readiness, Account/World source authority, recovery and activation holds remain. From 8e45ee03dce0e571de0c9dc3e3d7db5462baeef8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:57:57 +1300 Subject: [PATCH 03/11] Contain legacy Entity mutation ingress and prove terminal World retry guard --- .../api-contracts.md | 8 ++- .../runtime-and-data.md | 4 +- .../runtime-and-data.md | 2 +- .../world-creation-workflow.md | 2 +- .../gameplay-rules-entities-and-effects.md | 18 ++--- .../world-runtime-and-movement.md | 2 + .../controller/CraftingController.java | 31 ++++----- .../EntityMutationEffectReplayService.java | 3 +- .../controller/CraftingControllerTest.java | 66 ++++++++++--------- .../impl/EntityManagementGrpcServiceTest.java | 62 +++++++++++++++++ ...EntityMutationEffectReplayServiceTest.java | 30 ++++++--- .../WorldLifecycleCommandServiceImplTest.java | 64 ++++++++++++++++++ 12 files changed, 220 insertions(+), 72 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 0db89021b6..41b7d404ec 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -34,7 +34,7 @@ Recovery request/recovery identity conflicts use an explicit owner conflict sign The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. At the canonical roster bridge, the owner supplies `game_instance_uuid` as already canonical, non-nil UUID text under the shared [Identifier Format Conventions](../../system-architecture-identifier-glossary.md#identifier-format-conventions). That boundary contract does not change the generic assignment digest path: it hashes the exact opaque owner-supplied text and does not infer aliases, parse, or normalize it. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. -The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. +The legacy crafting REST adapters `POST /crafting/recipes` and `GET /crafting/recipes/{id}` fail closed with HTTP `501` and `CRAFTING_UNAVAILABLE` before request-body parsing, numeric recipe-ID parsing, or dispatch to the crafting service. Valid, malformed and absent POST bodies and valid or malformed GET IDs receive the same denial once routed to these adapters. The ping-only authoritative OpenAPI omits crafting; these denied adapters grant no tenant, recipe or item authority. The underlying crafting service/repository remains unsuitable for exposure until the target tenant-bound authorization and item-reference checks below are implemented and proved. The live `CharacterController`, `InventoryController`, `EquipmentController`, and `FriendController` REST handlers are also legacy direct adapters. They remain runtime-reachable behind baseline bearer authentication and their implemented tenant-access checks. @@ -55,10 +55,14 @@ The current response includes: - `entities[]`, each with the live proto fields `entityId`, `displayName`, `entityType`, `role`, `stateFlags`, `visionPriority`, `reloadHint`, `visible`, and `visibleRef`. - `error` when the current adapter cannot produce the response. +## Replay-guarded runtime mutations + +Runtime item, equipment and container mutations using `EntityMutationEffectReplayService` require a nonblank `effectId`. Missing, empty or whitespace-only identity returns `INVALID_ARGUMENT` at the gRPC adapter before replay-table access or owner mutation; there is no direct-execution fallback. Nonblank identities retain the current operation-name and stored-response replay checks. This guard does not establish the target typed target, namespace/scope/fence or immutable request-digest enforcement, nor concurrent first-apply safety; those remaining limits belong to [Runtime and Data](./runtime-and-data.md#implementation-status). + ## REST - `GET /ping` – basic health check returning `"pong"`. -- Entity Management does not advertise a supported player-facing REST route. The live `POST /crafting/recipes` and `GET /crafting/recipes/{id}` handlers remain **current legacy implementation drift** documented in the implementation status above, but are omitted from the authoritative OpenAPI because they are unsupported/nonconformant until the stated SessionContext tenant binding, tenant-qualified lookup/update, and same-tenant item-reference checks are implemented and proved. Unsupported/non-advertised here means absent from the authoritative contract, not HTTP-denied at runtime. +- Entity Management does not advertise a supported player-facing REST route. The legacy crafting adapters are denied as described in [Implementation Status](#implementation-status) and omitted from the authoritative OpenAPI; activation requires the target tenant-bound authorization and item-reference checks. ```bash curl http://localhost:8080/ping diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 09ea58ca5c..62618e3675 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -9,10 +9,10 @@ This document defines Entity Management’s runtime model, persistence ownership The explicitly enabled local demo owner-authentication client makes at most three Account calls, each with the existing five-second deadline and a 250 ms delay between attempts. Only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` may retry; domain credential failures, authorization refusal and invalid returned ownership still fail before Entity seeding. Interruption and exhausted retries abort startup without substituting an identity. This is bounded fixture startup resilience, not production authentication or permission to rewrite retained owners. -- The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. +- The legacy crafting REST adapters deny before parsing or owner dispatch under the [Entity API contract](./api-contracts.md#implementation-status). The underlying crafting service still trusts caller-selected tenant/item inputs and uses unqualified recipe lookups; tenant-bound authorization, qualified read/update predicates and same-tenant item ownership remain prerequisites for exposing it. - World owns guarded, manually composed initial `character_location` storage and its unregistered placement/read boundary. General movement, occupancy and NPC location remain unqualified; `room_instance` is topology, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. -- Current runtime item/equipment/container mutation RPCs that carry an `effectId` use `entity_mutation_effects` as the domain-local replay table. Entity Management records the applied protobuf response for `{tenantId, effectId}` and returns that stored response on duplicate delivery so `GET`, `DROP`, `PUT`, `TAKE`, `WEAR`, and `REMOVE` do not double-apply after Game Session replay or retry. Requests with a blank `effectId` bypass this table and execute directly; that fallback is current compatibility behavior, not a safe gameplay admission path. This is the current durable effect-replay guard, not a replacement tick-watermark implementation. +- Runtime item/equipment/container mutation RPCs require a nonblank `effectId` under the [Entity API contract](./api-contracts.md#replay-guarded-runtime-mutations) before replay lookup or mutation. The current `entity_mutation_effects` table stores the applied protobuf response for `{tenantId, effectId}` for duplicate delivery of `GET`, `DROP`, `PUT`, `TAKE`, `WEAR` and `REMOVE`; this is a domain-local replay guard, not a replacement tick-watermark implementation. - The `entitymanagement.mutation.effect.execution{operation,effect_status}` metric distinguishes first apply, replay/no-op, in-progress conflict, reported reuse outcome, and unreadable stored-response outcomes. - This current `{tenantId,effectId}` identity is not the target ADR 0054 participant guard: the replay record persists only the operation/status/payload result and reuse checks only the operation name. It does not yet persist or validate the typed target, namespace/scope/fence, or immutable request digest, and changed operation, target, or request reuse is not yet proven fail-closed. - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. 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 b0730c6f7b..49d8a48db7 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -13,7 +13,7 @@ - The registered `ApplyWorldDesignMutation` handler now fails closed before its former remote Game Design Draft-state read or local mutation dispatch. The owner-local mutation algorithm remains in `WorldDesignMutationServiceImpl`, but no registered ingress reaches it; existing V25 owner/fence persistence and direct-writer serialization are implemented, but the registered mutation request supplies no complete Game Design epoch/publication-fence authority. This is containment, not proof of Published-template immutability or completed write authorization. The target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). - The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The existing owner schema and shared-fence race proof cover local serialization; the combined source foundation prepares separate additive wire definitions and strict Common clients/codecs, without registered runtime handlers; subsequent standalone World owner consumers have bounded storage/transport qualification under controlled fixtures, without genuine publication authority: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. The registered RPC remains closed until the complete caller/tenant authorization and owner publication proof are implemented; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. - Procedural-generation persistence has a current identity gap: `V21__scoped_generation_rules.sql` creates a unique index over nullable `scope_type`/`scope_id`. Under PostgreSQL, multiple NULLs are distinct, so unscoped rows can duplicate the same `(tenant_id, version_id, name)` and destabilize deterministic generation-rule identity/digests. The current scope-aware repository lookup also compares nullable scope columns with SQL `=`, so it cannot retrieve an unscoped row. The target schema and mutation path must either prohibit unscoped rows or provide an explicit null-safe schema/query uniqueness contract, with focused proof; procedural-generation readiness remains blocked until that contract is enforced. -- The source-first termination correction compares a terminal retry’s `terminationRequestId` before returning the retained snapshot. Different identities fail closed; matching retries retain the existing request-ID replay semantics. `WorldLifecycleCommandServiceImplTest` source unit cases cover matching retained `TERMINATED` replay and mismatched-ID rejection. Separate controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization; controlled predecessor PostgreSQL and authenticated mTLS proof also covers same-identity replay and different-identity conflict. The full frozen-owner-snapshot acknowledgement and final-CAS workflow and Temporal retry behavior remain unqualified. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records detailed proof attribution and the broader lifecycle gaps. +- The source-first termination correction compares a terminal retry’s `terminationRequestId` before returning the retained snapshot. Only the exact retained identity replays successfully; a different request or missing retained identity fails closed before cleanup or mutation. Focused source unit cases cover exact retained replay, changed request identity, and absent retained identity. Separate controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization; controlled predecessor PostgreSQL and authenticated mTLS proof also covers same-identity replay and different-identity conflict. The full frozen-owner-snapshot acknowledgement and final-CAS workflow and Temporal retry behavior remain unqualified. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records detailed proof attribution and the broader lifecycle gaps. - The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. Temporal lost-response gaps remain as described below. - The current Weather path fails closed while its aggregate selector and typed effect fence remain unresolved: `WorldEventServiceImpl.scheduleEvent` rejects `WEATHER_CHANGE` before persistence, and the due-event sweep leaves retained Weather rows unprocessed without changing `region_instance.weather`. Region-bearing non-Weather scheduling also rejects a region outside the event's exact tenant/game-instance scope. This is containment, not Weather implementation or a disposition for retained Weather events; the owner still needs the accepted selector, effect identity/fence, safe reconciliation, and production-shaped proof before admitting Weather. - The non-Weather due-event query now requires a referenced `region_instance` to match the event's tenant/game-instance scope, and the processor defensively leaves a returned mismatch unprocessed. Focused service tests cover wrong-scope and valid rows, and Docker-backed PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior; local execution requires Docker/Testcontainers. `V16` still has only a scalar region FK, so retained-data/composite-ownership migration and readback remain separate open work. diff --git a/design/architecture/microservices/world-management-service/world-creation-workflow.md b/design/architecture/microservices/world-management-service/world-creation-workflow.md index 802977ed6b..54e25d96ba 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -15,7 +15,7 @@ The cross-platform workflow placement and adopter-proof requirements are owned b ## Implementation Status -The current first implementation cut exposes four synchronous lifecycle commands: `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance`, and `TerminateWorldInstance`. The first three create, admit, or fail a prepared instance; `TerminateWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId)` is the only live cleanup seam. Game Session reads fresh lifecycle state through `GetWorldInstanceLifecycle` immediately before termination. Termination accepts `ACTIVE -> TERMINATING`, invokes the current Entity cleanup seam, deletes the runtime `world_event`, `room_instance_exit`, `room_instance`, `zone_instance`, and `region_instance` subset, and then saves `TERMINATED` while retaining terminal lifecycle evidence. It does not yet implement the target frozen required-owner snapshot and ownership-registry revision, per-owner durable acknowledgements, complete registered World-owned cleanup, or final all-owner lifecycle CAS. A `TERMINATED` retry now compares `terminationRequestId` before returning: a different request identity fails with `IDEMPOTENCY_CONFLICT`, while a matching identity returns the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` source unit cases cover matching retained replay and mismatched-ID rejection. Separately, controlled retained-predecessor owner and PostgreSQL proof covers `TERMINATING` retention when Entity cleanup fails, rollback, and successful local finalization. Controlled predecessor fixtures also prove same-identity replay and different-identity rejection over native PostgreSQL and authenticated mTLS socket paths. These tests remain limited to that predecessor fixture scope; they do not prove the full frozen-owner-snapshot acknowledgement and final-CAS workflow or Temporal retry/recovery behavior. These live commands are not proof of the target cross-service termination workflow. +The current first implementation cut exposes four synchronous lifecycle commands: `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance`, and `TerminateWorldInstance`. The first three create, admit, or fail a prepared instance; `TerminateWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId)` is the only live cleanup seam. Game Session reads fresh lifecycle state through `GetWorldInstanceLifecycle` immediately before termination. Termination accepts `ACTIVE -> TERMINATING`, invokes the current Entity cleanup seam, deletes the runtime `world_event`, `room_instance_exit`, `room_instance`, `zone_instance`, and `region_instance` subset, and then saves `TERMINATED` while retaining terminal lifecycle evidence. It does not yet implement the target frozen required-owner snapshot and ownership-registry revision, per-owner durable acknowledgements, complete registered World-owned cleanup, or final all-owner lifecycle CAS. A `TERMINATED` retry compares `terminationRequestId` before returning: only the exact retained identity returns the snapshot; a changed request or missing retained identity fails with `IDEMPOTENCY_CONFLICT` before cleanup or mutation. Focused source unit cases cover exact retry, changed identity, and absent retained identity. Separately, controlled retained-predecessor owner and PostgreSQL proof covers `TERMINATING` retention when Entity cleanup fails, rollback, and successful local finalization. Controlled predecessor fixtures also prove same-identity replay and different-identity rejection over native PostgreSQL and authenticated mTLS socket paths. These tests remain limited to that predecessor fixture scope; they do not prove the full frozen-owner-snapshot acknowledgement and final-CAS workflow or Temporal retry/recovery behavior. These live commands are not proof of the target cross-service termination workflow. The run-owned fixture remains disabled by default. The retained predecessor bootstrap prepares through the generic `PrepareWorldInstance` RPC; activation and `ACTIVE` replay remain available through the existing lifecycle commands. Canonical preparation is a separate explicit prepare-only World owner operation and is not dispatched by the generic prepare RPC. World retains the original `PREPARING` epoch and complete fixture binding digest for exact prepare replay. Canonical activation and `ACTIVE` replay for the explicit canonical fixture variant remain closed. The canonical evidence and replay contract is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), and current controlled native proof and packaged runtime limits are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 7327993634..50441ff57c 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -86,11 +86,11 @@ The corrected Game Logic full gate passes in 1m49s, freshly executing nine Postg The prepared typed Account intake boundary carries a complete selected gameplay-rule source binding and immutable authorization, recovery and terminal-settlement evidence. It preserves the current stricter gameplay-rule manifest validation, including numeric stat values. Its Account unit/static/format and five PostgreSQL cases pass, and the corrected Common socket/static/format gate passes; exact scopes and earlier failed large-wire fixtures are attributed in the Account prerequisite tracker. Controlled upstream evidence is not genuine Game Design authoring or Game Logic retention. The prepared Game Logic retention owner and Game Design selected-source/receipt pipeline now have controlled standalone composition proof, as described in [Selected gameplay-rule retention and receipt composition](#selected-gameplay-rule-retention-and-receipt-composition); they remain unregistered and do not qualify the launch-descriptor consumer or genuine release authority. Selected-full Entity schema 3 and Automation schema 6 convergence remains a separate unfinished producer/consumer obligation; retained release attestations 1–3 keep their original meaning. See the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) for owner and proof scope. -The live implementation is strongest in item containment and transfer, durable effect replay for requests carrying a nonblank `effectId`, and the first evaluated actor-state/effect seams. Entity mutation requests with a blank `effectId` still execute directly without the replay ledger; this compatibility path is not safe gameplay-admission proof, and focused replay/readiness remains blocked until ingress rejects blank IDs or supplies a valid trusted ID. Entity Management also has crafting-oriented query structures and version-scoped recipe rows, but there is no complete player crafting/material-consumption flow yet. The broader authored-action, generic actor, targeting, resource-cost, and combat models remain incomplete. Cross-service proof is strongest on the bounded item, LOOK, movement, and nonblank-effect replay paths; broader gameplay orchestration is still represented more by service-level tests and slice-oriented fixtures than by full production integration. +The live implementation is strongest in item containment and transfer, durable effect replay for requests carrying a nonblank `effectId`, and the first evaluated actor-state/effect seams. Entity replay-guarded mutations now reject blank `effectId` values before replay lookup or owner mutation under the [Entity API contract](../../architecture/microservices/entity-management-service/api-contracts.md#replay-guarded-runtime-mutations); broader participant identity, request-digest and concurrent first-apply safety remain incomplete. Entity Management also has crafting-oriented query structures and version-scoped recipe rows, but there is no complete player crafting/material-consumption flow yet. The broader authored-action, generic actor, targeting, resource-cost, and combat models remain incomplete. Cross-service proof is strongest on the bounded item, LOOK, movement, and nonblank-effect replay paths; broader gameplay orchestration is still represented more by service-level tests and slice-oriented fixtures than by full production integration. -Current residual: the crafting handlers remain runtime-reachable legacy implementation drift, but their paths and schemas are omitted from the authoritative Entity OpenAPI; the REST adapter is therefore unsupported/nonconformant rather than a public contract. The deployed Entity HTTP layer still requires only an `AUTHENTICATED` bearer and does not authorize that caller to the supplied tenant. It trusts caller-supplied tenant, recipe, and item identifiers. The existing crafting proof is happy-path only; tenant-qualified recipe lookup/update, same-tenant result/ingredient ownership, and cross-tenant negative proof remain open. +The legacy crafting REST adapters now deny before parsing or owner dispatch under the [Entity API contract](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). The retained service/persistence seam still lacks tenant-qualified recipe lookup/update and same-tenant result/ingredient ownership; these remain activation prerequisites, together with cross-tenant negative proof. -The capability-table CRUD entry below refers only to this legacy persistence/service-controller seam; it is not a supported public REST API or gameplay crafting flow. +The capability-table CRUD entry below refers only to this legacy service/persistence seam behind denied controllers; it is not a supported public REST API or gameplay crafting flow. PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). The preparation adds opaque UUID/quarantine metadata, canonical assignment/receipt/roster storage, and manually composed unregistered source services. Existing legacy consumers retain develop behavior. Authenticated owner provenance, real caller/controller/execution replacement, runtime quarantine enforcement, and gameplay activation remain later work; storage fixtures do not close those gaps. @@ -109,12 +109,12 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata and ordinary Account UUID storage, wire/service/DTO receiving, nested-copy carriers and Account-authenticated demo seeding, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy numeric owner rows remain retained without invented UUID projection; new owner-resolved actors remain excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded and PLAYER_CREATED runtime projections and their separate purpose-specific reference reads are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention, exact canonical actor-repository read isolation, and ordinary Account UUID storage/receiver isolation. Focused public copy-carrier owner-isolation coverage is added in [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.java); R1311 passes the three carrier cases with no failures, errors, or skips. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. The bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites pass within R981, whose aggregate remains failed on the separate Game Session membership fixture and frontier/static checks; complete-suite and production limits remain. The distinct PLAYER_CREATED proof passes three Entity ingress units and 22 native creation/projection/mTLS cases in R840, with Entity static recovery in R842. R882/R883 supply receiving proof with their original failed aggregates and separate R884 static recovery. R898 adds 20 staged receiving cases on the reconciled parent for the bounded PLAYER_CREATED projection/reference, World receiving and Game Session region-consumer components, including retention of the first timeline across a later actor’s fresh region grant. Their scopes and limits are attributed by the [Player Access tracker](./player-access-and-session.md#canonical-new-admission-components); those historical results do not qualify a newer head. Current R1128 receiving checks for uniform refusal and independent historical digest proof pass as recorded in [Validation and Proof](#validation-and-proof). | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [EntityManagementRequestReaders.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [EntityManagementGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java); [TestDataSeeder.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java); [EntityPlayerCreatedRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeProjectionRepository.java); [EntityPlayerCreatedRuntimeReferenceService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java); [Entity V1023 player-created runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1023__player_created_runtime_projection.sql); [Entity V1024 ordinary Account UUID ownership](../../../services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java); [EntityPlayerCreatedRuntimeReferenceIngressTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java); [CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java); [OrdinaryAccountUuidOwnerPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java); [EntityManagementGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java); [CharacterControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java); [TestDataSeederTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. Ordinary UUID wire/service/DTO/seed receiving and actual Account-authenticated fresh-image smoke are qualified with their component and runtime limits in [Player Access](./player-access-and-session.md#ordinary-uuid-issuer-and-receiving); canonical actor promotion, registration and public admission remain held. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | -| GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | +| GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank `effectId` values reject before replay lookup or mutation. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID refusal is qualified by the focused receiving cases recorded below. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql); [EntityMutationEffectReplayService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java); [EntityManagementGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical target/scope/fence/request-digest enforcement and concurrent first-apply safety remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | | GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads are live; ability and skill progression is not. | `proven` - focused character progression and actor-state tests cover the bounded XP/level seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | -| GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence and CRUD APIs exist; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused crafting controller/service tests cover recipe persistence and validation; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | +| GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence exists behind denied legacy REST adapters; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused service tests cover recipe persistence and validation; controller denial cases pass receiving qualification; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | ## Canonical Design Sources @@ -163,11 +163,11 @@ The live transfer contract deliberately rejects an already-moved item by default Current Game Session implementation persists a stable same-batch `effectKey` and derives `effectId` from `tickBatchId` plus that key (`command:`); durable tick staging/replay rejects missing or blank command IDs before effect selection, so the private helper's defensive `command-text::slot:` branch is unreachable in the live tick path and is not a no-commandId recovery identity. Same-batch duplicate keys are rejected. Focused replay tests exercise restart drain, ownership-fence checks, stale-executor requeue, and local result mappings (`APPLIED`, `REPLAY_NOOP`, and `REJECTED`); they do not establish canonical cross-service participant-guard identity, effect terminalization, or proof that an ambiguous or rejected attempt cannot be reapplied. The command-linked identity does not establish the accepted effect identity/replay contract, which remains unimplemented and unproved here. Accepted command-plan and root-allocation requirements are defined in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); implementation and focused proof remain incomplete. See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) for the accepted effect rules and [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation) for participant-guard behavior. -The bounded owner-local replay implementations are: Movement's `effectId`-keyed idempotency service tied to session-context mutation; Entity Management's one mutation replay row per `{tenantId,effectId}` for validated, nonblank effect IDs, with the applied protobuf response for item, equipment, and container mutations, plus a separate `ApplyActorCondition` path that uses the temporary `sourceId` adapter. The focused Entity proof is limited to those nonblank-ID item/equipment/container and actor-condition paths: Entity mutation paths that accept blank effect IDs can bypass the replay table, while `ApplyActorCondition` rejects blank source identity before replay lookup. The Entity replay record also does not bind canonical target/scope/fence/request-digest evidence, so operation-only reuse is not proven fail-closed. Game Session has local replay records per `{tenantId,sessionId,effectId}` for `SAY`, `WHISPER`, `TELL`, `AFK`, `BLOCK`, and the bounded authored-action path, re-delivering actor-facing output without re-invoking the mutation handler. Social Groups persists `effect_id` with a `{tenantId,effectId}` uniqueness boundary and can return the stored chat DTO for a sequential duplicate whose first row was already committed; concurrent first-apply replay remains unproved. These are implementation boundaries and proof status, not the target participant-guard contract. +The bounded owner-local replay implementations are: Movement's `effectId`-keyed idempotency service tied to session-context mutation; Entity Management's one mutation replay row per `{tenantId,effectId}` for validated, nonblank effect IDs, with the applied protobuf response for item, equipment, and container mutations, plus a separate `ApplyActorCondition` path that uses the temporary `sourceId` adapter. The focused Entity proof is limited to those nonblank-ID item/equipment/container and actor-condition paths: replay-guarded mutation paths reject blank effect IDs before lookup or mutation, while `ApplyActorCondition` rejects blank source identity before replay lookup. The Entity replay record also does not bind canonical target/scope/fence/request-digest evidence, so operation-only reuse is not proven fail-closed. Game Session has local replay records per `{tenantId,sessionId,effectId}` for `SAY`, `WHISPER`, `TELL`, `AFK`, `BLOCK`, and the bounded authored-action path, re-delivering actor-facing output without re-invoking the mutation handler. Social Groups persists `effect_id` with a `{tenantId,effectId}` uniqueness boundary and can return the stored chat DTO for a sequential duplicate whose first row was already committed; concurrent first-apply replay remains unproved. These are implementation boundaries and proof status, not the target participant-guard contract. The shared execution helper currently keeps Game Session communication, AFK, action-state, and authored-action replay lookup/save/delivery behavior aligned. Existing metrics distinguish first-apply and replay/no-op outcomes through `gamesession.durable.effect.execution{command,effect_status,gameplay_result}` and Entity Management mutation execution metrics. This remains a bounded adoption set rather than a universal cross-service guard table; broader participant-guard propagation and cross-service replay proof remain incomplete. The target root/participant binding and outcome aggregation are owned by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). -Replay-status qualification: the GR-3.2 implementation and verification entries below describe the nonblank-`effectId` item/equipment/container replay-ledger path only. Those mutation requests still have a blank-ID compatibility direct-execution path that bypasses the Entity replay ledger. `ApplyActorCondition` is a separate exception: it has no dedicated `effectId`; its temporary adapter carries the durable ID in `sourceId`, which Entity uses as the replay key and source provenance. Existing replay tests therefore do not establish safe replay protection for every mutation ingress; focused proof and full-ingress replay readiness remain blocked until each ingress has a valid trusted replay identity. +Replay-status qualification: the GR-3.2 implementation and verification entries below describe the nonblank-`effectId` item/equipment/container replay-ledger path only. Those mutation requests reject blank IDs before replay lookup or owner mutation. `ApplyActorCondition` is a separate exception: it has no dedicated `effectId`; its temporary adapter carries the durable ID in `sourceId`, which Entity uses as the replay key and source provenance. Existing replay tests therefore do not establish safe replay protection for every mutation ingress; focused proof and full-ingress replay readiness remain blocked until each ingress has a valid trusted replay identity. ### Actor State and Typed Effects @@ -193,6 +193,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +R1422 passes all 83 selected Entity cases: six denied crafting controller cases, three replay-owner cases and 74 gRPC adapter cases. These cover valid, malformed and absent crafting input without service dispatch, null/empty/whitespace mutation identity before repository/supplier effects, and a real replay-service gRPC `INVALID_ARGUMENT` response. Enabled affected static analysis, full Java formatting, Entity packaging, capability tracking and documentation checks pass. Thirty-four selected World lifecycle units pass in the same aggregate. These are focused local adapter/owner results; they do not establish real PostgreSQL first-apply concurrency, complete participant identity, a player crafting path or current remote CI. + Current receiving R1128 passes all 32 selected native executions: 22 Entity creation/projection/reference cases and ten Game Session region-owner cases. Projection and service refusals now use the same bounded FAILED_PRECONDITION description, including actual quarantine read failures. Historical V1050.5 rows are seeded using the independent parent response reconstruction and length-prefixed SHA256 formula; a separate comparison verifies current preseeded compatibility before upgrade. Existing retained row/xmin/history and exact refusal assertions remain. Enabled affected Entity main/integration and Game Session integration analysis, formatting and documentation pass. This focused receiving proof does not replace current published-head CI or qualify production registration, upstream custody or public admission. - A restored positive Entity terminal-read socket case freshly passes with affected Common Platform Core test Checkstyle, SpotBugs and formatting. The actual `GrpcEntitySelectedSourceIntakeTerminalReadClient` receives a complete canonical receipt larger than the ordinary 4 MiB gRPC default over loopback mTLS, within the declared wire bound; the server verifies the Account workload and original request, and the client returns the exact original receipt and authorization bytes. The existing [terminal client test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java) previously covered only missing-receipt transport and server pinning; that case retains its earlier execution attribution. The complete authorization, World inventory and Entity receipt are controlled fixtures, and the shared test PKI differs from the donor's inline PKI helper. This is client/codec transport proof, not genuine issuer or recipient storage, currentness, settlement, runtime registration or handoff closure. @@ -217,7 +219,7 @@ Current receiving R1128 passes all 32 selected native executions: 22 Entity crea - Item cross-service proof covers WebSocket `LOGIN` / `PLAY` / `LOOK` / `INV HERE` / `GET` / `CONTAINER` / `PUT` / `TAKE` / `DROP`, including parser preservation, room-ground changes, holder refreshes, request context, quantity, and nonblank durable effect ids; the equipment loop covers `EQUIPMENT` / `WEAR` / `REMOVE` and `SLOT_INCOMPATIBLE`. - Telnet proof covers the corresponding command surface through TCP Proxy and Gateway, including room-ground pickup/drop, nearby containers, equipment bind/unbind, incompatible equipment, and Entity Management request/effect assertions. Typed first-party WebSocket proof covers enriched inventory views and every typed item mutation; shared transcript prose remains covered for generic WebSocket and Telnet. - Item and transfer unit/integration proofs cover non-empty container movement, duplicate container definitions, independent duplicate item targeting, stable refs across holders, stack merge/family preservation and ambiguity rejection, stale-source rejection, already-at-destination rejection, tenant validation, and shared guarded transfer across all live holder kinds. -- Durable replay proof covers deterministic effect identity, same-batch uniqueness, restart drain behavior, movement replay, the bounded Entity Management item/equipment/container path for nonblank `effectId` plus the separate `ApplyActorCondition` path using its temporary `sourceId` adapter, Game Session communication/activity/action-state/authored-action replay, and Social Groups duplicate message delivery on the committed-duplicate/sequential path; it does not establish concurrent first-apply replay. Focused tests include `RedisMovementEffectIdempotencyServiceTest`, `DefaultDurableGameplayCommandExecutionServiceTest`, and `EntityMutationEffectReplayServiceTest`, including stored authored-action replay without handler reinvocation. These tests do not establish replay protection for every Entity mutation ingress; blank-ID compatibility execution and the overloaded actor-condition identity remain explicit gaps. +- Durable replay proof covers deterministic effect identity, same-batch uniqueness, restart drain behavior, movement replay, the bounded Entity Management item/equipment/container path for nonblank `effectId` plus the separate `ApplyActorCondition` path using its temporary `sourceId` adapter, Game Session communication/activity/action-state/authored-action replay, and Social Groups duplicate message delivery on the committed-duplicate/sequential path; it does not establish concurrent first-apply replay. Focused tests include `RedisMovementEffectIdempotencyServiceTest`, `DefaultDurableGameplayCommandExecutionServiceTest`, and `EntityMutationEffectReplayServiceTest`, including stored authored-action replay without handler reinvocation. These tests do not establish replay protection for every Entity mutation ingress; the overloaded actor-condition identity, complete participant binding and concurrent first-apply safety remain explicit gaps. - Actor-state proof covers the Entity Management evaluator composition and the separate `STATUS` transport path. The documented service checklists also record successful relevant Entity Management, Game Design, Game Logic, Game Session, and cross-service item validation. - LOOK-oriented entity proof covers deterministic empty-room and multi-entity listings. World Management test fixtures define rooms and exits, while Entity Management's `firemud.look.rooms` test configuration supplies stable player, NPC, and item transcript data. - Inventory query and mutation proof covers hidden implementation-owned inventory containers, room-ground containers, equipment bindings, basic query filtering, successful audited transfers, failed transfers with no committed audit row, and deterministic retry correlation. 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 6f0a89f93c..95d73b39b5 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -345,6 +345,8 @@ These links add decision provenance only; they do not upgrade world runtime, lif ### Validation and Proof +R1422 passes all 34 selected `WorldLifecycleCommandServiceImplTest` units, including direct proof of the already implemented terminal request-ID guard: exact retained retry returns the snapshot, while a different request or missing retained ID refuses without cleanup or writes. Enabled affected static analysis, full Java formatting and documentation checks pass, together with 83 selected Entity cases in the same aggregate. World dependencies are controlled collaborators; this does not qualify Temporal closed-workflow reconciliation, complete owner cleanup or current remote CI. + - LOOK proof covers deterministic World room snapshots and exits, visible Entity room-ground data, authenticated command behavior, structured scope-marker composition, dependency failure propagation, and WebSocket/Telnet rendering parity. Target Game Session floor allocation, Game Logic propagation, participant served-through/component-version validation, stale-floor retry, and mixed-region/scope/epoch rejection remain unproved. DROP/PICKUP proof also lacks stale World `TargetingFactSnapshot` location/version rejection and same-root replay coverage. Movement proof covers valid directional exits, invalid or missing exits, missing-room behavior, downstream failures, unauthenticated commands, Game Session binding mutation, destination auto-LOOK, non-disconnecting failures, pipeline traversal, and reconnect-after-move. Focused automated proof now covers returning destination room context and obtaining a destination-bound `LOOK` before the local binding effect. Authoritative World Management location mutation is not yet proven because that write contract is not implemented. - Runtime-room convergence proof covers canonical World Management emission and malformed-id rejection, row/record exit mapping, canonical room cache keys, shared readers at Game Logic and Entity Management ingress, attestation issuance and claims, session-routing scrubbing, movement idempotency, automation event payloads, and Game Session outbound validation before transport dispatch. Ordinary fixtures use `R-...`; legacy `room-...`, bare numeric, uppercase, or malformed forms remain only in negative tests. - Lifecycle proof covers the durable world creation, activation, termination, and failure path plus the operator-facing lifecycle read surface; the extracted command path is the local non-Temporal fallback. It does not prove Temporal lost-response activity retries, ACTIVE-aware start compensation, exact terminal retries after workflow completion, or closed-workflow reconciliation. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java index 7ccd580154..07ac6d2448 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java @@ -1,34 +1,31 @@ package net.firedevops.firemud.entitymanagement.controller; -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.ApiResponse; +import net.firedevops.firemud.common.ErrorDetail; import net.firedevops.firemud.entitymanagement.dto.CraftingRecipeDto; -import net.firedevops.firemud.entitymanagement.service.CraftingService; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -/** REST endpoints for crafting recipes. */ +/** Fail-closed legacy crafting routes until tenant-bound owner authorization is implemented. */ @RestController @RequestMapping("/crafting/recipes") -@RequiredArgsConstructor public class CraftingController { - private final CraftingService craftingService; - @PostMapping - public ResponseEntity> create( - @Valid @RequestBody CraftingRecipeDto dto) { - CraftingRecipeDto result = craftingService.createRecipe(dto); - return ResponseEntity.ok(ApiResponse.success(result)); + public ResponseEntity> create() { + return unavailable(); } @GetMapping("/{id}") public ResponseEntity> get(@PathVariable String id) { - return EntityManagementRequestReaders.withBadRequest( - () -> - ResponseEntity.ok( - ApiResponse.success( - craftingService.getRecipe( - EntityManagementRequestReaders.requirePositivePathId(id, "id"))))); + return unavailable(); + } + + private ResponseEntity> unavailable() { + return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED) + .body( + ApiResponse.error( + new ErrorDetail( + "CRAFTING_UNAVAILABLE", "Crafting requires tenant-bound owner authorization"))); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java index 4e2d1e3756..3d2e458488 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java @@ -44,7 +44,8 @@ public T execute( Supplier mutation, ResponseParser parser) { if (!StringUtils.hasText(effectId)) { - return mutation.get(); + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, "Effect id is required for replay-guarded mutations"); } String normalizedEffectId = effectId.trim(); String normalizedOperationName = operationName.trim(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java index 1cde8200b6..2666ad7bc2 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java @@ -1,16 +1,13 @@ package net.firedevops.firemud.entitymanagement.controller; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.List; -import net.firedevops.firemud.entitymanagement.dto.CraftingIngredientDto; -import net.firedevops.firemud.entitymanagement.dto.CraftingRecipeDto; import net.firedevops.firemud.entitymanagement.service.CraftingService; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @@ -25,47 +22,37 @@ class CraftingControllerTest { @MockitoBean private CraftingService craftingService; - @Test - void getReturnsRecipe() throws Exception { - when(craftingService.getRecipe(7L)) - .thenReturn( - new CraftingRecipeDto( - 7L, 1L, "Torch", 14L, 1, List.of(new CraftingIngredientDto(3L, 1)))); + @AfterEach + void doesNotDispatchToLegacyCraftingOwner() { + verifyNoInteractions(craftingService); + } + @Test + void getDeniesBeforeReadingUnscopedRecipe() throws Exception { mockMvc .perform(get("/crafting/recipes/7")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.name").value("Torch")); + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); } @Test - void getRejectsMalformedIdBeforeDispatch() throws Exception { + void getDeniesMalformedIdBeforeDispatch() throws Exception { mockMvc .perform(get("/crafting/recipes/not-a-number")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("id must be numeric")); - - verifyNoInteractions(craftingService); + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); } @Test - void getRejectsZeroIdBeforeDispatch() throws Exception { + void getDeniesZeroIdBeforeDispatch() throws Exception { mockMvc .perform(get("/crafting/recipes/0")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("id must be positive")); - - verifyNoInteractions(craftingService); + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); } @Test - void createReturnsRecipe() throws Exception { - when(craftingService.createRecipe(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> invocation.getArgument(0, CraftingRecipeDto.class)); - + void createDeniesBeforeWritingCallerSuppliedTenantAndItems() throws Exception { mockMvc .perform( post("/crafting/recipes") @@ -81,8 +68,23 @@ void createReturnsRecipe() throws Exception { "ingredients": [{"itemId": 3, "quantity": 1}] } """)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.resultItemId").value(14)); + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); + } + + @Test + void createReturnsUnavailableWhenBodyIsMissing() throws Exception { + mockMvc + .perform(post("/crafting/recipes")) + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); + } + + @Test + void createReturnsUnavailableWhenBodyIsMalformed() throws Exception { + mockMvc + .perform(post("/crafting/recipes").contentType(MediaType.APPLICATION_JSON).content("{")) + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("CRAFTING_UNAVAILABLE")); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 76f8604229..b6fa3f706a 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.entitymanagement.dto.RoomEntityDto; import net.firedevops.firemud.entitymanagement.dto.RuntimeInstanceCleanupResultDto; import net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser; +import net.firedevops.firemud.entitymanagement.repository.EntityMutationEffectRepository; import net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService; import net.firedevops.firemud.entitymanagement.service.ActorStateService; import net.firedevops.firemud.entitymanagement.service.CharacterService; @@ -3540,6 +3541,67 @@ public void onCompleted() {} verifyNoInteractions(equipmentService); } + @Test + void wearEquipmentRejectsBlankEffectIdBeforeMutation() { + PingService pingService = Mockito.mock(PingService.class); + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityDraftDesignDigestService digestService = + Mockito.mock(EntityDraftDesignDigestService.class); + EquipmentService equipmentService = Mockito.mock(EquipmentService.class); + InventoryService inventoryService = Mockito.mock(InventoryService.class); + ContainerService containerService = Mockito.mock(ContainerService.class); + RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); + EntityMutationEffectRepository effectRepository = + Mockito.mock(EntityMutationEffectRepository.class); + EntityMutationEffectReplayService replayService = + new EntityMutationEffectReplayService(effectRepository, new SimpleMeterRegistry()); + SessionContext.setContext( + "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + EntityManagementGrpcService service = + new EntityManagementGrpcService( + pingService, + characterService, + digestService, + equipmentService, + inventoryService, + containerService, + roomEntityService, + replayService, + Mockito.mock(EntityUpgradeValidationService.class), + attestationService(), + new SimpleMeterRegistry()); + + AtomicReference ref = new AtomicReference<>(); + service.wearEquipment( + WearEquipmentItemRequest.newBuilder() + .setTenantId("1") + .setCharacterId("7") + .setGameInstanceId("GI-1") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setItemId("99") + .setEffectId(" \t ") + .build(), + new StreamObserver<>() { + @Override + public void onNext(WearEquipmentItemResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals( + "Effect id is required for replay-guarded mutations", ref.get().getError().getMessage()); + verifyNoInteractions(equipmentService, effectRepository); + } + @Test void removeEquipmentReturnsRemovedItem() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java index 4b8eb9fa96..2f51dd30bc 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java @@ -1,7 +1,7 @@ package net.firedevops.firemud.entitymanagement.service.impl; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.never; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -25,15 +25,29 @@ class EntityMutationEffectReplayServiceTest { new EntityMutationEffectReplayService(repository, meterRegistry); @Test - void executeWithoutEffectIdBypassesReplayLedger() { - PickupItemFromRoomResponse expected = pickupResponse("Torch"); + void executeRejectsMissingOrBlankEffectIdBeforeMutation() { + AtomicBoolean mutationCalled = new AtomicBoolean(false); + Supplier mutation = + () -> { + mutationCalled.set(true); + return pickupResponse("Torch"); + }; - PickupItemFromRoomResponse response = - service.execute( - 1L, null, "PickupItemFromRoom", () -> expected, PickupItemFromRoomResponse::parseFrom); + for (String effectId : new String[] {null, "", " \t "}) { + assertThatThrownBy( + () -> + service.execute( + 1L, + effectId, + "PickupItemFromRoom", + mutation, + PickupItemFromRoomResponse::parseFrom)) + .isInstanceOf(org.springframework.web.server.ResponseStatusException.class) + .hasMessageContaining("Effect id is required"); + } - assertThat(response).isSameAs(expected); - verify(repository, never()).findByTenantIdAndEffectId(Mockito.anyLong(), Mockito.anyString()); + assertThat(mutationCalled).isFalse(); + Mockito.verifyNoInteractions(repository); } @Test diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 33a3516917..9e37876dec 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -14,6 +15,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -478,6 +480,68 @@ void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { verify(regionInstanceRepository).deleteByTenantIdAndGameInstanceId(42L, 101L); } + @Test + void terminatedWorldInstanceReturnsStoredSnapshotForExactRetryWithoutEffects() { + WorldInstance instance = activeWorldInstance(); + instance.setStatus("TERMINATED"); + instance.setTerminationRequestId("term-1"); + instance.setLifecycleEpoch(4L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance)); + + var snapshot = service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop"); + + assertEquals("TERMINATED", snapshot.status()); + assertEquals(4L, snapshot.lifecycleEpoch()); + assertEquals("term-1", instance.getTerminationRequestId()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verifyNoInteractions( + entityManagementClient, + worldEventRepository, + roomInstanceExitRepository, + roomInstanceRepository, + zoneInstanceRepository, + regionInstanceRepository); + } + + @Test + void terminatedWorldInstanceRejectsDifferentOrMissingRetainedRequestIdWithoutEffects() { + WorldInstance instance = activeWorldInstance(); + instance.setStatus("TERMINATED"); + instance.setTerminationRequestId("term-1"); + instance.setLifecycleEpoch(4L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance)); + + IllegalArgumentException differentRequest = + assertThrows( + IllegalArgumentException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-2", "stop")); + assertTrue(differentRequest.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); + assertEquals("TERMINATED", instance.getStatus()); + assertEquals(4L, instance.getLifecycleEpoch()); + assertEquals("term-1", instance.getTerminationRequestId()); + + instance.setTerminationRequestId(null); + IllegalArgumentException missingRetainedRequest = + assertThrows( + IllegalArgumentException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + assertTrue(missingRetainedRequest.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); + assertEquals("TERMINATED", instance.getStatus()); + assertEquals(4L, instance.getLifecycleEpoch()); + assertNull(instance.getTerminationRequestId()); + + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verifyNoInteractions( + entityManagementClient, + worldEventRepository, + roomInstanceExitRepository, + roomInstanceRepository, + zoneInstanceRepository, + regionInstanceRepository); + } + @Test void terminateWorldInstanceDoesNotCommitTerminationWhenWorldCleanupFails() { WorldInstance instance = activeWorldInstance(); From 4f13634c416dbc16f8c2d29776e38e7f7038b2fc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:24:31 +1300 Subject: [PATCH 04/11] Record queued review timer diagnostic recovery --- design/project-management/ai-observations.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index db3484cfe2..ca8bfbed76 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -22,3 +22,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Recovery from a pending patch call needs a fresh file read. - Root saw a patch call remain pending and later used an alternate edit without rereading after that call ended. The original patch had landed, so the local certificate test briefly contained duplicate fixture setup. Diff inspection caught and removed it before publication, and the corrected contract was rerun successfully. Next: inspect current scoped bytes after an uncertain mutation before constructing recovery; a pending result does not establish that no edit occurred. + +- `2026-11-01` (Pacific/Auckland): MCP queued-review diagnostics omitted the automatic cooldown timer. + - For #3367 Hosted operation `8342161ac32a0a606eb54ee1bc949d32`, MCP showed queued state with no attempt or wait metadata, even with diagnostics selected. The role-bound CLI exposed the retained automatic retry deadline, so this was undispatched cooldown rather than an active review fence. Root initially delayed qualified publication while treating that distinction as unknown, then withdrew only the old undispatched intent and queued the corrected head. No active provider work was cancelled. The installed review skill also described the older terminal/manual cooldown path. Next: align MCP diagnostics and the installed guide with the durable timer; exact evidence was sent to FireController Worker and the correction to Overseer. From 49a01acceef7703c1f604dd7c6ab2c4a222e39d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:32:06 +1300 Subject: [PATCH 05/11] Record combined publication and Entity containment runtime proof --- .../game-authoring-publishing-and-activation.md | 2 ++ 1 file changed, 2 insertions(+) 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 da402b2e10..5896a922bd 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 @@ -517,3 +517,5 @@ No competing current authority is recorded for settings, versioned release bundl | Temporal | Durable publish/readiness workflow execution where long-lived waiting is required | Workflow identity/status surfaced through canonical reads | R1420 local publication-containment proof passes 178 selected Game Design cases: 156 unit cases and 22 actual PostgreSQL/application cases, alongside 50 Automation units in the combined gate. The real patch owner records a manifest-unavailable terminal failure while retaining its canonical DRAFT tuple; exact retry preserves complete attempt/candidate rows and `xmin`, a genuine pre-existing PENDING original remains unchanged without redispatch, and the direct owner transaction rolls back its Draft/attempt writes together. Launch-descriptor SQL and current full-version offline transaction controls also pass. Participant gates are controlled collaborators, not genuine publication or manifest authority. Enabled affected static analysis, full formatting, both service packages and documentation checks pass; fresh canonical image-lane held smoke builds all eleven applications from carried source `eaee2ed9af91c2a6ad217df0b00d1bea16dcbb5f` and passes direct backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial. Authenticated run-owned teardown and independent exact-project queries find no containers, networks or volumes. Successful public admission and production publication/activation remain unproved. Existing full-publication authorization refusal, production manifest/readiness, Account/World source authority, recovery and activation holds remain. + +The same coherent #2856 receiving boundary includes the remaining compatible Entity mutation/crafting containment and direct World terminal-request proof. Their detailed qualification stays with [Gameplay Rules](./gameplay-rules-entities-and-effects.md#validation-and-proof) and [World Runtime](./world-runtime-and-movement.md#validation-and-proof). Together the separate R1420 and R1422 gates pass 345 selected cases: 323 units and 22 actual PostgreSQL/application cases, with their original source attribution and controlled-input limits. After receiving current credential/audit parents and their review corrections, fresh canonical image-lane held smoke builds all eleven applications from `4f13634c416dbc16f8c2d29776e38e7f7038b2fc` and passes backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial. Run-owned teardown and independent exact-project checks find no containers, networks or volumes. This qualifies the combined local runtime, not a complete service suite, successful public admission, positive publication or production authority. From effccb6ba35079254af9c5086814e7a22ae0cc1c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:50:39 +1300 Subject: [PATCH 06/11] ci: partition Game Session checks four ways with complete proof --- .github/scripts/run-gradle-module-checks.sh | 7 +- .github/workflows/ci.yml | 18 +- .github/workflows/validation-summary.yml | 31 +- build.gradle.kts | 22 +- .../architecture/system-architecture-cicd.md | 8 +- .../tests/ci-lightweight-scope-contract.sh | 42 +- .../tests/ci-validation-summary-contract.sh | 48 +- .../tests/test_slow_service_ci_partition.py | 127 +++- .../slow_service_ci_test_partition.py | 159 ++--- .../slow_service_ci_test_partition_plan.json | 567 +++++++++--------- 10 files changed, 602 insertions(+), 427 deletions(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 107641ea57..0a71d56502 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -6,9 +6,10 @@ readonly ROOT_DIR readonly MODULE="${1:-}" readonly PARTITION="${2:-full}" if [[ $# -lt 1 || $# -gt 2 || ! "$MODULE" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ || \ - ( ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" ) && $# -eq 2 && "$PARTITION" != "1" && "$PARTITION" != "2" ) || \ + ( "$MODULE" == "account-service" && "$PARTITION" != "full" && "$PARTITION" != "1" && "$PARTITION" != "2" ) || \ + ( "$MODULE" == "game-session-service" && "$PARTITION" != "full" && ! "$PARTITION" =~ ^[1-4]$ ) || \ ( "$MODULE" != "account-service" && "$MODULE" != "game-session-service" && $# -eq 2 && "$PARTITION" != "full" ) ]]; then - echo "usage: run-gradle-module-checks.sh [full|1|2] (Account and Game Session partitions only)" >&2 + echo "usage: run-gradle-module-checks.sh [full|partition] (Account: 1-2; Game Session: 1-4)" >&2 exit 64 fi @@ -47,7 +48,7 @@ if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" ) --run-attempt "${GITHUB_RUN_ATTEMPT:-0}" \ --output-dir "$PARTITION_DIR" \ "${CLASS_DIR_ARGS[@]}" - CHECK_ARGS+=("-PslowServiceCiPartition=$PARTITION") + CHECK_ARGS+=("-PslowServiceCiPartitionModule=$MODULE" "-PslowServiceCiPartition=$PARTITION") fi # Keep the original recovery policy and complete check; diagnostics never retry it. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ad6a48a97..741449f8f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -146,13 +146,11 @@ jobs: lightweight_only: false, }; } - const partitionedSlowServices = new Set(["account-service", "game-session-service"]); + const slowServicePartitionCounts = { "account-service": 2, "game-session-service": 4 }; outputs.module_check_matrix = outputs.affected_modules.flatMap((module) => - partitionedSlowServices.has(module) - ? [ - { module, partition: "1", "java-version": 21 }, - { module, partition: "2", "java-version": 21 }, - ] + slowServicePartitionCounts[module] + ? Array.from({ length: slowServicePartitionCounts[module] }, (_, index) => + ({ module, partition: String(index + 1), "java-version": 21 })) : [{ module, partition: "full", "java-version": 21 }] ); for (const [name, value] of Object.entries(outputs)) { @@ -1081,6 +1079,10 @@ jobs: with: egress-policy: audit + - name: 'Declare Game Session CI partition count: 4' + if: ${{ matrix.module == 'game-session-service' }} + run: ':' + - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -1279,7 +1281,7 @@ jobs: --selection-json "$SELECTION_PATH" \ --github-output "$GITHUB_OUTPUT" - - name: Download both effective Account partition artifacts + - name: Download all effective Account partition artifacts uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 continue-on-error: true with: @@ -1390,7 +1392,7 @@ jobs: --selection-json "$SELECTION_PATH" \ --github-output "$GITHUB_OUTPUT" - - name: Download both effective Game Session partition artifacts + - name: Download all effective Game Session partition artifacts uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 continue-on-error: true with: diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index b2107996a3..38741dccb9 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -177,10 +177,10 @@ jobs: for (const job of jobs) { if (fixedNames.has(job.name)) continue; if ([...aggregateNames.values()].includes(job.name)) continue; - const match = /^Build and Test \(([a-z0-9-]+)(?: \/ (full|[12]))?\)$/.exec(job.name || ""); + const match = /^Build and Test \(([a-z0-9-]+)(?: \/ (full|[1-4]))?\)$/.exec(job.name || ""); if (match && modules.has(match[1])) { const [, module, partition] = match; - if (partition && (slowServices.has(module) ? !["1", "2"].includes(partition) : partition !== "full")) { + if (partition && (slowServices.has(module) ? !(module === "game-session-service" ? ["1", "2", "3", "4"] : ["1", "2"]).includes(partition) : partition !== "full")) { throw new Error("Invalid module partition: " + job.name); } matrix.push({ job, module, partition: partition || null }); @@ -202,9 +202,32 @@ jobs: for (const module of slowServices) { const serviceMatrix = matrix.filter(entry => entry.module === module); const aggregate = aggregates.get(module); - const partitioned = serviceMatrix.length === 2 && + // Bind the selected count to this exact native source attempt, never a mutable branch. + // Old complete two-way Game Session jobs have native steps but no count marker. + // Empty step inventories cannot establish that historical shape: wholly skipped + // new jobs must not turn a truncated four-way matrix into an apparent old pair. + let expectedPartitions = "1,2"; + let invalidPlanMarkers = false; + if (module === "game-session-service" && serviceMatrix.some(entry => entry.partition !== null)) { + const markers = serviceMatrix.map(entry => { + const steps = entry.job.steps; + if (!Array.isArray(steps) || steps.length === 0 || steps.length > 100 || + steps.some(step => typeof step?.name !== "string")) return null; + return steps.filter(step => step.name.startsWith("Declare Game Session CI partition count:")); + }); + const fourWay = markers.some(entries => entries?.length > 0); + if (fourWay) { + expectedPartitions = "1,2,3,4"; + invalidPlanMarkers = markers.some(entries => entries?.length !== 1 || + entries[0].name !== "Declare Game Session CI partition count: 4"); + } else { + invalidPlanMarkers = markers.some(entries => entries === null); + } + } + const partitioned = !invalidPlanMarkers && + serviceMatrix.length === expectedPartitions.split(",").length && serviceMatrix.every(entry => entry.partition !== null) && - serviceMatrix.map(entry => entry.partition).sort().join(",") === "1,2"; + serviceMatrix.map(entry => entry.partition).sort().join(",") === expectedPartitions; const legacy = serviceMatrix.length === 1 && serviceMatrix[0].partition === null; if (serviceMatrix.length > 0 && !partitioned && !legacy) invalidSlowServiceMatrix = true; if (partitioned && ( diff --git a/build.gradle.kts b/build.gradle.kts index 6c9ab2df74..21bef3e652 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -91,6 +91,21 @@ tasks.register("compileBufGeneratedJava") { } val fullCheck = project.hasProperty("fullCheck") || System.getenv("CI") != null +val slowServiceCiPartitionCounts = mapOf("account-service" to 2, "game-session-service" to 4) +val slowServiceCiModules = slowServiceCiPartitionCounts.keys +val slowServiceCiPartition = providers.gradleProperty("slowServiceCiPartition").orNull +val slowServiceCiPartitionModule = providers.gradleProperty("slowServiceCiPartitionModule").orNull +if ((slowServiceCiPartition == null) != (slowServiceCiPartitionModule == null)) { + throw GradleException("slowServiceCiPartition and slowServiceCiPartitionModule must be supplied together") +} +if (slowServiceCiPartitionModule != null) { + val partitionCount = slowServiceCiPartitionCounts[slowServiceCiPartitionModule] + ?: throw GradleException("slowServiceCiPartitionModule must name an allowed slow service") + if (slowServiceCiPartition !in (1..partitionCount).map { it.toString() }) { + throw GradleException("slowServiceCiPartition is outside the selected module partition range") + } +} + val checkstyleToolVersion = "14.3.0" val spotbugsToolVersion = "4.10.5" val platformSettingsMetadataFiles = listOf( @@ -384,8 +399,6 @@ subprojects { if (file("src/test/java/integration").exists()) add("integrationTest") if (file("src/test/java/crossservice").exists()) add("crossServiceTest") } - val slowServiceCiModules = setOf("account-service", "game-session-service") - val slowServiceCiPartition = providers.gradleProperty("slowServiceCiPartition").orNull val slowServiceCiCoverageAggregate = providers.gradleProperty("slowServiceCiCoverageAggregate").orNull val slowServiceCiCoverageClassesDirectory = @@ -414,10 +427,7 @@ subprojects { } else { null } - if (project.name in slowServiceCiModules && slowServiceCiPartition != null) { - if (slowServiceCiPartition !in setOf("1", "2")) { - throw GradleException("slowServiceCiPartition must be 1 or 2") - } + if (project.name == slowServiceCiPartitionModule) { tasks.withType().configureEach { val selectorFile = layout.buildDirectory.file( "slow-service-ci-partition/" + project.name + diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 110bae2e61..f9118f5479 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -62,13 +62,13 @@ The fresh disposable [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081 The shipped [preservation contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) asserts canonical assessment, ordinary listener scope, and the retained fail-closed identity, evidence, chronology, history, admission, and confirmation boundaries. -Account Service and Game Session module validation each use two independent matrix partitions. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so both partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from both measured partitions. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. The existing Validation Gate requires every module matrix entry and the corresponding coverage aggregate when either slow service is affected. Ordinary local checks for both services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. +Account Service validation uses two independent matrix partitions and Game Session uses four. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the module’s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. The existing Validation Gate requires every module matrix entry and the corresponding coverage aggregate when either slow service is affected. Ordinary local checks for both services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. ## Workflow Structure Workflows live in the `.github/workflows/` directory. A typical pipeline runs on every pull request and on pushes to the long-lived publication branches (`develop` today, and `main` for release-oriented publication paths). -The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes current Build and Test module/partition records and requires both partitions and their matching aggregate for each affected Account or Game Session module, while retaining legacy unpartitioned module names for older source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. +The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account or Game Session module, while retaining attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. Serialization uses branch and immutable head SHA so superseded heads cannot evict current-head pending callbacks. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. @@ -108,9 +108,9 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Generates protobuf outputs to keep generated stubs aligned with the checked-in schemas. - Runs formatting and lint steps (Spotless, markdownlint, link checks). -- On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use two complete-check partitions; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. +- On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service uses two complete-check partitions and Game Session uses four; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. -- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies both partitions' selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. +- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile` and retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days. These reports expose startup, configuration, dependency and task durations without changing the selected checks, workers or recovery behavior. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. - Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. Native `--info` compiler identity lines come from the original check; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Cancellation/signal exits (128 or above) skip collection and diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original failing exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 3430d76bcc..80135b586f 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -34,6 +34,7 @@ done for expected in \ 'declare -a PREPARE_TASKS=(":${MODULE}:testClasses")' \ 'PREPARE_TASKS+=(":${MODULE}:${task_name}Classes")' \ + 'CHECK_ARGS+=("-PslowServiceCiPartitionModule=$MODULE" "-PslowServiceCiPartition=$PARTITION")' \ 'bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh"'; do require_contains "$MODULE_CHECK_WRAPPER" "$expected" done @@ -86,7 +87,7 @@ def evaluate_module_check_matrix(step, modules): if match is None: raise SystemExit("ci workflow: module check matrix builder is missing") partition_set = re.search( - r'(?m)^[ \t]*const partitionedSlowServices = new Set\([^\n]+\);', + r'(?m)^[ \t]*const slowServicePartitionCounts = \{[^\n]+\};', script[:match.start()], ) if partition_set is None: @@ -398,12 +399,14 @@ expected_matrix_rows = [ {"module": "account-service", "partition": "2", "java-version": 21}, {"module": "game-session-service", "partition": "1", "java-version": 21}, {"module": "game-session-service", "partition": "2", "java-version": 21}, + {"module": "game-session-service", "partition": "3", "java-version": 21}, + {"module": "game-session-service", "partition": "4", "java-version": 21}, {"module": "common-security", "partition": "full", "java-version": 21}, ] expanded_jobs = [dict(row) for row in matrix_rows] if expanded_jobs != expected_matrix_rows or len({ (row["module"], row["partition"]) for row in expanded_jobs -}) != 5: +}) != 7: raise SystemExit(f"ci workflow: matrix expansion lost or duplicated a job: {expanded_jobs!r}") require_contains( ci_compute_step, @@ -414,12 +417,12 @@ require_contains( require_contains( ci_compute_step, ("with", "script"), - 'const partitionedSlowServices = new Set(["account-service", "game-session-service"]);', + 'const slowServicePartitionCounts = { "account-service": 2, "game-session-service": 4 };', "ci workflow", ) for expected in ( - '{ module, partition: "1", "java-version": 21 },', - '{ module, partition: "2", "java-version": 21 },', + 'Array.from({ length: slowServicePartitionCounts[module] }', + 'partition: String(index + 1)', 'partition: "full"', '"java-version": 21', ): @@ -559,7 +562,7 @@ for module, job_id, display, prefix in ( select = find_step(ci, job_id, f"Select {display} artifacts from latest effective job outcomes", "ci workflow") require_contains(select, ("run",), "python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts", "ci workflow") require_contains(select, ("run",), f"--module {module}", "ci workflow") - download = find_step(ci, job_id, f"Download both effective {display} partition artifacts", "ci workflow") + download = find_step(ci, job_id, f"Download all effective {display} partition artifacts", "ci workflow") require_equal(download, ("continue-on-error",), "true", "ci workflow") require_equal(download, ("with", "artifact-ids"), "${{ steps.selection.outputs.artifact_ids }}", "ci workflow") verify = find_step(ci, job_id, f"Verify complete {display} partition and report union", "ci workflow") @@ -618,7 +621,7 @@ const testedMerge = "a".repeat(40), nativeHead = "b".repeat(40), baseSha = "c".r const wrongSha = "d".repeat(40); const repositoryFullName = `${owner}/${repository}`; const coreJobRows = ["account-service", "game-session-service"].flatMap((module, index) => - [1, 2].map(partition => ({ + Array.from({ length: module === "account-service" ? 2 : 4 }, (_, index) => index + 1).map(partition => ({ id: 100 + index * 10 + partition, run_id: runId, head_sha: nativeHead, name: `Build and Test (${module} / ${partition})`, status: "completed", conclusion: "success", started_at: "2026-10-30T01:00:00Z", @@ -631,7 +634,7 @@ const jobRows = coreJobRows.concat(Array.from({ length: 97 }, (_, index) => ({ started_at: "2026-10-30T01:00:00Z", completed_at: "2026-10-30T02:00:00Z", }))); const coreArtifactRows = ["account-service", "game-session-service"].flatMap((module, index) => - [1, 2].map(partition => ({ + Array.from({ length: module === "account-service" ? 2 : 4 }, (_, index) => index + 1).map(partition => ({ id: 700 + index * 10 + partition, name: `slow-service-ci-partition-${runId}-${testedMerge}-attempt-1-${module}-partition-${partition}`, expired: false, size_in_bytes: 1024, created_at: "2026-10-30T02:00:00Z", @@ -763,8 +766,8 @@ async function runFor(embedded, options = {}) { } (async () => { - assert.equal(jobRows.length, 101); - assert.equal(artifactRows.length, 101); + assert.equal(jobRows.length, 103); + assert.equal(artifactRows.length, 103); for (const embedded of input.scripts) { assert.ok(embedded.script.includes("capture-slow-service-provenance.cjs")); assert.ok(embedded.script.includes("module: process.env.CI_MODULE")); @@ -806,7 +809,7 @@ async function runFor(embedded, options = {}) { assert.equal(result.provenance.run.run_attempt, attempts); assert.equal(result.provenance.attempts.length, attempts); for (const attempt of result.provenance.attempts) { - assert.equal(attempt.jobs.length, 101); + assert.equal(attempt.jobs.length, jobRows.length); for (const job of attempt.jobs) { assert.equal(job.head_sha, result.provenance.run.head_sha); assert.equal(job.run_attempt, attempt.attempt, "raw API attempt is preserved per snapshot"); @@ -817,7 +820,7 @@ async function runFor(embedded, options = {}) { "attempt snapshots retain cloned job IDs", ); } - assert.equal(result.provenance.artifacts.items.length, 101); + assert.equal(result.provenance.artifacts.items.length, artifactRows.length); for (const artifact of result.provenance.artifacts.items) { assert.equal(artifact.workflow_run.head_sha, result.provenance.run.head_sha); } @@ -911,6 +914,21 @@ require_equal( ) gradle_build = Path(sys.argv[6]).read_text(encoding="utf-8") +root_configuration, subproject_configuration = gradle_build.split("subprojects {", 1) +for expected in ( + 'val slowServiceCiPartitionCounts = mapOf("account-service" to 2, "game-session-service" to 4)', + 'providers.gradleProperty("slowServiceCiPartitionModule").orNull', + 'if ((slowServiceCiPartition == null) != (slowServiceCiPartitionModule == null))', + 'slowServiceCiPartitionCounts[slowServiceCiPartitionModule]', + 'slowServiceCiPartition !in (1..partitionCount).map { it.toString() }', +): + if expected not in root_configuration: + raise SystemExit(f"build.gradle.kts: root partition/module binding is missing {expected!r}") +if 'if (project.name == slowServiceCiPartitionModule) {' not in subproject_configuration: + raise SystemExit("build.gradle.kts: selectors must apply only to the explicitly selected module") +if 'providers.gradleProperty("slowServiceCiPartition")' in subproject_configuration: + raise SystemExit("build.gradle.kts: partition arguments must be validated once before configuring subprojects") + test_logging_match = re.search( ( r"tasks\.withType\(\)\.configureEach\s*\{\s*" diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index d071a15eb6..b26ecedb47 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -32,6 +32,13 @@ script = next(step['with']['script'] for step in steps if step.get('name') == ' if '${{ needs.' in script or 'downloadArtifact' in script: raise SystemExit('Callback must reconstruct native jobs without PR artifacts or unavailable needs outputs') # The native name mapping must remain complete when CI adds/removes a job. +marker_steps = [step for step in ci['jobs']['build-and-test']['steps'] if step.get('name', '').startswith('Declare Game Session CI partition count:')] +if len(marker_steps) != 1 or marker_steps[0] != { + 'name': 'Declare Game Session CI partition count: 4', + 'if': "${{ matrix.module == 'game-session-service' }}", + 'run': ':', +}: + raise SystemExit('Four-way Game Session source must declare its native partition-plan marker') names = [job['name'] for job in ci['jobs'].values()] for name in names: if '${{' not in name and json.dumps(name, ensure_ascii=False) not in script: @@ -57,7 +64,7 @@ const pr = { number: 42, state: 'open', head: { sha: head, repo: { full_name: repository } }, base: { ref: 'develop', sha: base, repo: { full_name: repository } }, }; -const row = (name, id) => ({ id, name, run_id: 70, run_attempt: 1, head_sha: head, status: 'completed', conclusion: 'success' }); +const row = (name, id) => ({ id, name, run_id: 70, run_attempt: 1, head_sha: head, status: 'completed', conclusion: 'success', steps: [{ name: 'Harden runner', status: 'completed', conclusion: 'success' }] }); const jobs = payload.names.filter(name => !name.includes('${{')).map((name, i) => row(name, i + 1)); jobs.push( row('Build and Test (account-service / 1)', 90), @@ -250,6 +257,45 @@ async function noWrites(config, reject = false) { await noWrites({ jobs: clone(jobs).filter(x => x.name !== 'Build and Test (game-session-service / 2)') }, true); await noWrites({ jobs: clone(jobs).filter(x => x.name !== 'Game Session Coverage Aggregate') }, true); + const fourWay = clone(jobs); + fourWay.push(row('Build and Test (game-session-service / 3)', 95), row('Build and Test (game-session-service / 4)', 96)); + for (const job of fourWay.filter(job => job.name.startsWith('Build and Test (game-session-service /'))) { + job.steps.push({ name: 'Declare Game Session CI partition count: 4', status: 'completed', conclusion: 'success' }); + } + const successfulFourWay = harness({ jobs: fourWay }); await successfulFourWay.run(); + assert.match(successfulFourWay.calls.creates[0].body, /Service build\/test matrix: `success`/); + const failedFourWay = clone(fourWay); + failedFourWay.find(job => job.name === 'Build and Test (game-session-service / 4)').conclusion = 'failure'; + failedFourWay.find(job => job.name === 'Game Session Coverage Aggregate').conclusion = 'skipped'; + const failedFourWayRun = harness({ jobs: failedFourWay }); await failedFourWayRun.run(); + assert.match(failedFourWayRun.calls.creates[0].body, /Service build\/test matrix: `failure`/); + for (const missing of [ + ['Build and Test (game-session-service / 3)'], + ['Build and Test (game-session-service / 4)'], + ['Build and Test (game-session-service / 3)', 'Build and Test (game-session-service / 4)'], + ]) await noWrites({ jobs: clone(fourWay).filter(job => !missing.includes(job.name)) }, true); + for (const mutate of [ + job => { job.steps = []; }, + job => { delete job.steps; }, + job => { job.steps.pop(); }, + job => { job.steps[1].name = 'Declare Game Session CI partition count: 2'; }, + job => { job.steps.push(clone(job.steps[1])); }, + ]) { + const invalid = clone(fourWay); + mutate(invalid.find(job => job.name === 'Build and Test (game-session-service / 4)')); + await noWrites({ jobs: invalid }, true); + } + const unmarkedFourWay = clone(fourWay); + for (const job of unmarkedFourWay) job.steps = [{ name: 'Harden runner' }]; + await noWrites({ jobs: unmarkedFourWay }, true); + const skippedIncompleteFourWay = clone(jobs); + for (const job of skippedIncompleteFourWay.filter(job => job.name.startsWith('Build and Test (game-session-service /'))) { + job.steps = []; job.conclusion = 'skipped'; + } + await noWrites({ jobs: skippedIncompleteFourWay }, true); + await noWrites({ jobs: [...clone(fourWay), row('Build and Test (account-service / 3)', 97)] }, true); + await noWrites({ jobs: [...clone(fourWay), { ...clone(fourWay.find(job => job.name === 'Build and Test (game-session-service / 4)')), id: 97 }] }, true); + const skipped = clone(jobs).filter(x => !x.name.startsWith('Build and Test (')); skipped.find(x => x.name === 'Account Coverage Aggregate').conclusion = 'skipped'; skipped.find(x => x.name === 'Game Session Coverage Aggregate').conclusion = 'skipped'; diff --git a/dev-tools/tests/test_slow_service_ci_partition.py b/dev-tools/tests/test_slow_service_ci_partition.py index 5a696b7894..3ab7345cb5 100644 --- a/dev-tools/tests/test_slow_service_ci_partition.py +++ b/dev-tools/tests/test_slow_service_ci_partition.py @@ -23,13 +23,13 @@ def make_plan(module="account-service", run_attempt="2"): - return { + plan = { "schema_version": 1, "module": module, "source_revision": SOURCE_SHA, "run_id": RUN_ID, "run_attempt": str(run_attempt), - "partition_count": 2, + "partition_count": PARTITION.PARTITION_COUNTS[module], "tasks": { "test": { "class_universe": [ @@ -48,6 +48,14 @@ def make_plan(module="account-service", run_attempt="2"): }, } + if module == "game-session-service": + for partition in (3, 4): + name = f"net.example.Known{partition}Test" + plan["tasks"]["test"]["class_universe"].append(name) + plan["tasks"]["test"]["expected_test_classes"].append(name) + plan["tasks"]["test"]["assignments"][name] = partition + return plan + def job(module, partition, attempt, conclusion="success", start=START, finish=MIDDLE, run_id=70, source=SOURCE_SHA): return { @@ -147,7 +155,7 @@ def make_provenance( pull_request = None display_title = "CI — Validation develop" associations = [] - return { + provenance = { "run": { "id": 70, "head_sha": native_head, @@ -193,6 +201,16 @@ def make_provenance( }, } + for partition in range(3, PARTITION.PARTITION_COUNTS[module] + 1): + for snapshot in provenance["attempts"]: + snapshot["jobs"].append(job(module, partition, snapshot["attempt"], source=native_head)) + snapshot["total_count"] += 1 + provenance["artifacts"]["items"].append( + artifact(module, partition, 1, 700 + partition + 10, source=tested_source, native_head=native_head) + ) + provenance["artifacts"]["total_count"] += 1 + return provenance + def write_artifact(root, plan, partition, attempt): name = ( @@ -238,18 +256,11 @@ def prepare_aggregate(root, module, provenance): input_dir.mkdir() plan = make_plan(module) artifacts = { - 1: write_artifact( - input_dir, - plan, - 1, - provenance["resolved"]["partitions"]["1"]["attempt"], - ), - 2: write_artifact( - input_dir, - plan, - 2, - provenance["resolved"]["partitions"]["2"]["attempt"], - ), + partition: write_artifact( + input_dir, plan, partition, + provenance["resolved"]["partitions"][str(partition)]["attempt"], + ) + for partition in PARTITION.partitions_for(module) } selection_path = root / "selection.json" selection_path.write_text(json.dumps(provenance), encoding="utf-8") @@ -321,22 +332,21 @@ def test_historical_assignments_and_new_classes_form_complete_disjoint_plans_for historical, class_access_flags_by_task={task: access_flags}, ) - first = PARTITION.partition_manifest(plan, 1) - second = PARTITION.partition_manifest(plan, 2) - PARTITION.validate_partition_pair(first, second) + manifests = [ + PARTITION.partition_manifest(plan, partition) + for partition in PARTITION.partitions_for(module) + ] + PARTITION.validate_partitions(manifests) self.assertEqual( - first["tasks"][task]["assignments"][known_class], + plan["tasks"][task]["assignments"][known_class], known_entry["partition"], ) - self.assertEqual( - set(first["tasks"][task]["selected_classes"]) - | set(second["tasks"][task]["selected_classes"]), - discovered[task], - ) - self.assertFalse( - set(first["tasks"][task]["selected_classes"]) - & set(second["tasks"][task]["selected_classes"]) - ) + selected_groups = [ + set(manifest["tasks"][task]["selected_classes"]) + for manifest in manifests + ] + self.assertEqual(set().union(*selected_groups), discovered[task]) + self.assertEqual(sum(map(len, selected_groups)), len(discovered[task])) def test_nested_compiled_classes_stay_with_their_outer_class(self): with tempfile.TemporaryDirectory() as temporary: @@ -426,9 +436,10 @@ def test_nested_runnable_group_survives_abstract_outer_and_nonrunnable_types_sta self.assertEqual( task_plan["expected_test_classes"], [abstract_test, real_test] ) - first = PARTITION.partition_manifest(plan, 1) - second = PARTITION.partition_manifest(plan, 2) - PARTITION.validate_partition_pair(first, second) + PARTITION.validate_partitions([ + PARTITION.partition_manifest(plan, partition) + for partition in PARTITION.partitions_for(plan["module"]) + ]) missing_metadata = dict(access_flags) missing_metadata.pop(marker) @@ -864,7 +875,7 @@ def test_aggregate_ignores_only_the_spring_metadata_sidecar(self): SOURCE_SHA, "2", ), - 2, + 4, ) copied_paths = { path.relative_to(verified_classes_dir).as_posix() @@ -976,6 +987,56 @@ def test_aggregate_rejects_missing_junit_for_a_selected_test_class(self): "2", ) + def test_four_way_retry_requires_every_latest_effective_partition(self): + module = "game-session-service" + provenance = make_provenance(module, native_head=PR_HEAD_SHA) + resolved = PARTITION.resolve_effective_artifacts( + provenance, module, RUN_ID, SOURCE_SHA, "2" + ) + self.assertEqual(set(resolved["partitions"]), {"1", "2", "3", "4"}) + self.assertEqual( + [resolved["partitions"][str(partition)]["attempt"] for partition in range(1, 5)], + [1, 2, 1, 1], + ) + for partition in (3, 4): + with self.subTest(partition=partition): + failed = copy.deepcopy(provenance) + failed["attempts"][1]["jobs"][partition - 1]["conclusion"] = "failure" + with self.assertRaisesRegex(ValueError, f"partition {partition} latest effective.*failure"): + PARTITION.resolve_effective_artifacts(failed, module, RUN_ID, SOURCE_SHA, "2") + missing = copy.deepcopy(provenance) + missing["artifacts"]["items"] = [ + item for item in missing["artifacts"]["items"] + if not item["name"].endswith(f"partition-{partition}") + ] + missing["artifacts"]["total_count"] -= 1 + with self.assertRaisesRegex(ValueError, f"partition {partition} physical attempt 1 has missing"): + PARTITION.resolve_effective_artifacts(missing, module, RUN_ID, SOURCE_SHA, "2") + + def test_four_way_union_and_measured_classes_include_later_partitions(self): + module = "game-session-service" + plan = make_plan(module) + manifests = [PARTITION.partition_manifest(plan, partition) for partition in range(1, 5)] + PARTITION.validate_partitions(manifests) + with self.assertRaisesRegex(ValueError, "every module partition exactly once"): + PARTITION.validate_partitions(manifests[:2]) + with self.assertRaisesRegex(ValueError, "every module partition exactly once"): + PARTITION.validate_partitions([*manifests[:3], manifests[2]]) + overlap = copy.deepcopy(manifests) + overlap[3]["tasks"]["test"]["selected_classes"].append("net.example.KnownOneTest") + with self.assertRaisesRegex(ValueError, "overlap between partitions"): + PARTITION.validate_partitions(overlap) + for partition in (3, 4): + with self.subTest(partition=partition), tempfile.TemporaryDirectory() as temporary: + selection = PARTITION.selection_document(make_provenance(module), module, RUN_ID, SOURCE_SHA, "2") + input_dir, selection_path, verified_classes_dir, artifacts = prepare_aggregate(Path(temporary), module, selection) + (artifacts[partition] / "classes/java/main/net/example/MeasuredService.class").write_bytes( + classfile_bytes("net/example/ChangedService") + ) + with self.assertRaisesRegex(ValueError, "class bytes differ"): + PARTITION.verify_aggregate(input_dir, selection_path, verified_classes_dir, module, RUN_ID, SOURCE_SHA, "2") + self.assertFalse(verified_classes_dir.exists()) + def test_partition_pair_rejects_incomplete_class_union(self): plan = make_plan() first = PARTITION.partition_manifest(plan, 1) @@ -983,7 +1044,7 @@ def test_partition_pair_rejects_incomplete_class_union(self): broken = copy.deepcopy(second) broken["tasks"]["test"]["selected_classes"] = [] with self.assertRaisesRegex(ValueError, "test class union is incomplete"): - PARTITION.validate_partition_pair(first, broken) + PARTITION.validate_partitions([first, broken]) if __name__ == "__main__": diff --git a/dev-tools/validation/slow_service_ci_test_partition.py b/dev-tools/validation/slow_service_ci_test_partition.py index 40bfdacc1b..4de40d38e1 100644 --- a/dev-tools/validation/slow_service_ci_test_partition.py +++ b/dev-tools/validation/slow_service_ci_test_partition.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Select, provenance-check, and aggregate the two slow-service CI partitions.""" +"""Select, provenance-check, and aggregate the module-specific slow-service CI partitions.""" from __future__ import annotations @@ -17,7 +17,11 @@ PLAN_PATH = Path(__file__).with_name("slow_service_ci_test_partition_plan.json") SERVICES = ("account-service", "game-session-service") -PARTITION_COUNT = 2 +PARTITION_COUNTS = {"account-service": 2, "game-session-service": 4} + + +def partitions_for(module: str) -> range: + return range(1, PARTITION_COUNTS[module] + 1) TEST_CLASS_SUFFIX = re.compile(r"(?:^Test.*|.*(?:Test|Tests|TestCase))$") SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$") NON_RUNNABLE_TEST_TYPE_FLAGS = 0x0200 | 0x2000 @@ -25,17 +29,20 @@ ARTIFACT_PATTERN = re.compile( r"^slow-service-ci-partition-(?P[1-9][0-9]*)-" r"(?P[0-9a-f]{40})-attempt-(?P[1-9][0-9]*)-" - r"(?P[a-z0-9]+(?:-[a-z0-9]+)*)-partition-(?P[12])$" + r"(?P[a-z0-9]+(?:-[a-z0-9]+)*)-partition-(?P[1-9][0-9]*)$" ) def load_historical_plan(module: str, path: Path = PLAN_PATH) -> dict[str, Any]: plan = json.loads(path.read_text(encoding="utf-8")) - if plan.get("schema_version") != 1 or plan.get("partition_count") != PARTITION_COUNT: + if plan.get("schema_version") != 2: raise ValueError(f"unsupported slow-service partition plan: {path}") if module not in SERVICES or module not in plan.get("services", {}): raise ValueError(f"unsupported slow-service module: {module}") - return plan["services"][module] + historical = plan["services"][module] + if historical.get("partition_count") != PARTITION_COUNTS[module]: + raise ValueError(f"unsupported partition count for {module}: {path}") + return historical def is_test_class(class_name: str) -> bool: @@ -198,8 +205,8 @@ def build_plan( raise ValueError(f"unsupported slow-service module: {module}") historical = historical_plan or load_historical_plan(module) task_plans: dict[str, Any] = {} - global_load = {1: 0.0, 2: 0.0} - global_test_count = {1: 0, 2: 0} + global_load = dict.fromkeys(partitions_for(module), 0.0) + global_test_count = dict.fromkeys(partitions_for(module), 0) pending_unknown_tests: list[tuple[str, str, float]] = [] pending_other_classes: list[tuple[str, str]] = [] @@ -241,15 +248,15 @@ def build_plan( for task, class_name, estimate in sorted(pending_unknown_tests): partition = min( - (1, 2), key=lambda value: (global_load[value], global_test_count[value], value) + partitions_for(module), key=lambda value: (global_load[value], global_test_count[value], value) ) task_plans[task]["assignments"][class_name] = partition global_load[partition] += estimate global_test_count[partition] += 1 - other_class_count = {1: 0, 2: 0} + other_class_count = dict.fromkeys(partitions_for(module), 0) for task, class_name in sorted(pending_other_classes): - partition = min((1, 2), key=lambda value: (other_class_count[value], value)) + partition = min(partitions_for(module), key=lambda value: (other_class_count[value], value)) task_plans[task]["assignments"][class_name] = partition other_class_count[partition] += 1 @@ -258,7 +265,7 @@ def build_plan( assignments = task_plan["assignments"] if set(assignments) != universe: raise ValueError(f"partition assignment is incomplete for {task}") - if any(partition not in (1, 2) for partition in assignments.values()): + if any(partition not in partitions_for(module) for partition in assignments.values()): raise ValueError(f"partition assignment is invalid for {task}") return { @@ -267,14 +274,14 @@ def build_plan( "source_revision": source_revision, "run_id": str(run_id), "run_attempt": str(run_attempt), - "partition_count": PARTITION_COUNT, + "partition_count": PARTITION_COUNTS[module], "tasks": task_plans, } def partition_manifest(plan: dict[str, Any], partition: int) -> dict[str, Any]: - if partition not in (1, 2): - raise ValueError("partition must be 1 or 2") + if partition not in partitions_for(plan["module"]): + raise ValueError("partition is outside the module partition range") tasks = {} for task, task_plan in plan["tasks"].items(): tasks[task] = { @@ -305,52 +312,52 @@ def write_partition(plan: dict[str, Any], partition: int, output_dir: Path) -> P return manifest_path -def validate_partition_pair( - first: dict[str, Any], second: dict[str, Any] -) -> dict[str, Any]: - if first.get("module") not in SERVICES or first.get("module") != second.get("module"): +def validate_partitions(manifests: list[dict[str, Any]]) -> dict[str, Any]: + if not manifests or manifests[0].get("module") not in SERVICES: raise ValueError("aggregate requires matching supported service partitions") - if first.get("partition") != 1 or second.get("partition") != 2: - raise ValueError("aggregate requires partition 1 and partition 2 exactly once") - if first.get("partition_count") != PARTITION_COUNT or second.get("partition_count") != PARTITION_COUNT: - raise ValueError("aggregate requires the complete two-partition plan") - for identity in ("run_id", "source_revision"): - if first.get(identity) != second.get(identity): - raise ValueError(f"partition artifacts have different {identity}") - common_first = copy.deepcopy( - {key: value for key, value in first.items() if key not in {"partition", "run_attempt"}} - ) - common_second = copy.deepcopy( - {key: value for key, value in second.items() if key not in {"partition", "run_attempt"}} - ) - for manifest in (common_first, common_second): - for task_plan in manifest["tasks"].values(): + first = manifests[0] + module = first["module"] + expected = set(partitions_for(module)) + if len(manifests) != len(expected) or {item.get("partition") for item in manifests} != expected: + raise ValueError("aggregate requires every module partition exactly once") + common = None + for manifest in manifests: + if manifest.get("module") != module: + raise ValueError("aggregate requires matching supported service partitions") + if manifest.get("partition_count") != PARTITION_COUNTS[module]: + raise ValueError("aggregate requires the complete module partition plan") + for identity in ("run_id", "source_revision"): + if first.get(identity) != manifest.get(identity): + raise ValueError(f"partition artifacts have different {identity}") + candidate = copy.deepcopy({ + key: value for key, value in manifest.items() + if key not in {"partition", "run_attempt"} + }) + for task_plan in candidate["tasks"].values(): task_plan.pop("selected_classes", None) - if common_first != common_second: - raise ValueError("partition artifacts do not share one discovered class plan") + if common is not None and common != candidate: + raise ValueError("partition artifacts do not share one discovered class plan") + common = candidate for task, task_plan in first["tasks"].items(): - second_task = second["tasks"].get(task) - if second_task is None: - raise ValueError(f"partition 2 is missing test task {task}") universe = set(task_plan["class_universe"]) assignments = task_plan["assignments"] - if set(assignments) != universe: - raise ValueError(f"class assignment is incomplete for {task}") - first_selected = set(task_plan["selected_classes"]) - second_selected = set(second_task["selected_classes"]) - if first_selected & second_selected: - raise ValueError(f"test classes overlap between partitions for {task}") - if first_selected | second_selected != universe: + if set(assignments) != universe or any(value not in expected for value in assignments.values()): + raise ValueError(f"class assignment is incomplete or invalid for {task}") + union: set[str] = set() + for manifest in manifests: + selected = set(manifest["tasks"][task]["selected_classes"]) + if union & selected: + raise ValueError(f"test classes overlap between partitions for {task}") + union.update(selected) + if union != universe: raise ValueError(f"test class union is incomplete for {task}") - if first_selected != { - name for name, assigned in assignments.items() if assigned == 1 - }: - raise ValueError(f"partition 1 selector disagrees with its assignment for {task}") - if second_selected != { - name for name, assigned in assignments.items() if assigned == 2 - }: - raise ValueError(f"partition 2 selector disagrees with its assignment for {task}") + for manifest in manifests: + partition = manifest["partition"] + if set(manifest["tasks"][task]["selected_classes"]) != { + name for name, assigned in assignments.items() if assigned == partition + }: + raise ValueError(f"partition {partition} selector disagrees with its assignment for {task}") return first @@ -583,7 +590,7 @@ def resolve_effective_artifacts( attempt_map: dict[int, dict[str, Any]] = {} expected_names = { partition: f"Build and Test ({module} / {partition})" - for partition in (1, 2) + for partition in partitions_for(module) } latest_jobs: dict[int, tuple[int, dict[str, Any]]] = {} @@ -605,7 +612,7 @@ def resolve_effective_artifacts( if total_count < 0: raise ValueError(f"workflow attempt {attempt_number} job count is invalid") ids: set[int] = set() - matches: dict[int, list[dict[str, Any]]] = {1: [], 2: []} + matches: dict[int, list[dict[str, Any]]] = {partition: [] for partition in partitions_for(module)} for job in jobs: if not isinstance(job, dict): raise TypeError(f"workflow attempt {attempt_number} jobs must be objects") @@ -658,7 +665,10 @@ def resolve_effective_artifacts( match = ARTIFACT_PATTERN.fullmatch(name) if not match: raise ValueError(f"slow-service partition artifact name is malformed: {name}") - if match.group("module") == module: + artifact_module = match.group("module") + if artifact_module not in SERVICES or int(match.group("partition")) not in partitions_for(artifact_module): + raise ValueError(f"slow-service partition artifact is outside its module plan: {name}") + if artifact_module == module: if int(match.group("run_id")) != expected_run_id or match.group("source_revision") != source_revision: raise ValueError(f"partition artifact {name} has wrong-run or wrong-source identity") if int(match.group("attempt")) > expected_attempt: @@ -678,7 +688,7 @@ def resolve_effective_artifacts( selected: dict[str, Any] = {} selected_ids: set[int] = set() - for partition in (1, 2): + for partition in partitions_for(module): latest = latest_jobs.get(partition) if latest is None: raise ValueError(f"partition {partition} has no authoritative job outcome") @@ -781,21 +791,21 @@ def verify_aggregate( raise ValueError("saved artifact selection differs from authoritative Actions provenance") if not input_dir.is_dir(): - raise ValueError("could not retrieve both effective successful partition artifacts") + raise ValueError("could not retrieve all effective successful partition artifacts") artifacts = sorted(path for path in input_dir.iterdir() if path.is_dir()) expected_names = { resolved["partitions"][str(partition)]["artifact_name"] - for partition in (1, 2) + for partition in partitions_for(module) } if {path.name for path in artifacts} != expected_names: raise ValueError( - "aggregate requires exactly both latest-effective successful partition artifacts; " + "aggregate requires exactly all latest-effective successful partition artifacts; " f"found {[path.name for path in artifacts]}" ) manifests = {} artifact_directories = {} - for partition in (1, 2): + for partition in partitions_for(module): artifact_name = resolved["partitions"][str(partition)]["artifact_name"] artifact_dir = input_dir / artifact_name artifact_directories[partition] = artifact_dir @@ -820,17 +830,20 @@ def verify_aggregate( raise ValueError(f"partition {partition} selector manifest identifies another shard") manifests[partition] = manifest - common = validate_partition_pair(manifests[1], manifests[2]) - measured_classes = verify_identical_main_classes( - artifact_directories[1], artifact_directories[2] - ) + common = validate_partitions(list(manifests.values())) + measured_classes = None + for partition in partitions_for(module): + if partition != 1: + measured_classes = verify_identical_main_classes( + artifact_directories[1], artifact_directories[partition] + ) execution_data = [] - for partition in (1, 2): + for partition in partitions_for(module): artifact_name = resolved["partitions"][str(partition)]["artifact_name"] artifact_dir = input_dir / artifact_name execution_data.extend(verify_artifact_reports(artifact_dir, manifests[partition])) if not execution_data: - raise ValueError("aggregate has no JaCoCo execution data from either partition") + raise ValueError("aggregate has no JaCoCo execution data from any partition") copy_verified_main_classes( artifact_directories[1] / "classes" / "java" / "main", measured_classes, @@ -841,7 +854,7 @@ def verify_aggregate( f"Verified complete {module} partition coverage input: " f"{len(common['tasks'])} test tasks, " f"{sum(len(task['class_universe']) for task in common['tasks'].values())} " - "discovered class groups, identical measured production classes, both " + "discovered class groups, identical measured production classes, all " "partition reports, and latest effective same-run/source job provenance." ) return len(execution_data) @@ -892,7 +905,7 @@ def verify_identical_main_classes(first_artifact: Path, second_artifact: Path) - extra = sorted(set(second) - set(first)) raise ValueError( "partition measured production class inventories differ: " - f"partition 2 missing {missing}, extra {extra}" + f"compared partition missing {missing}, extra {extra}" ) for relative_path in sorted(first): if first[relative_path].read_bytes() != second[relative_path].read_bytes(): @@ -940,7 +953,7 @@ def build_parser() -> argparse.ArgumentParser: plan_parser = subparsers.add_parser("plan", help="write one slow-service shard selector") plan_parser.add_argument("--module", choices=SERVICES, required=True) - plan_parser.add_argument("--partition", type=int, choices=(1, 2), required=True) + plan_parser.add_argument("--partition", type=int, required=True) plan_parser.add_argument("--source-revision", required=True) plan_parser.add_argument("--run-id", required=True) plan_parser.add_argument("--run-attempt", required=True) @@ -959,7 +972,7 @@ def build_parser() -> argparse.ArgumentParser: select_parser.add_argument("--github-output", type=Path, required=True) aggregate_parser = subparsers.add_parser( - "verify-aggregate", help="require complete reports from both effective shard attempts" + "verify-aggregate", help="require complete reports from all effective shard attempts" ) aggregate_parser.add_argument("--module", choices=SERVICES, required=True) aggregate_parser.add_argument("--input-dir", type=Path, required=True) @@ -1015,11 +1028,11 @@ def main(argv: list[str] | None = None) -> int: ) artifact_ids = ",".join( str(document["resolved"]["partitions"][str(partition)]["artifact_id"]) - for partition in (1, 2) + for partition in partitions_for(args.module) ) with args.github_output.open("a", encoding="utf-8") as output: output.write(f"artifact_ids={artifact_ids}\n") - print(f"Selected both successful {args.module} partition artifact IDs: {artifact_ids}") + print(f"Selected all successful {args.module} partition artifact IDs: {artifact_ids}") return 0 verify_aggregate( args.input_dir, diff --git a/dev-tools/validation/slow_service_ci_test_partition_plan.json b/dev-tools/validation/slow_service_ci_test_partition_plan.json index 50abfac1b0..587b83aa7c 100644 --- a/dev-tools/validation/slow_service_ci_test_partition_plan.json +++ b/dev-tools/validation/slow_service_ci_test_partition_plan.json @@ -1,10 +1,10 @@ { "atomicity": "Each test-task/suite appears once per option. Nested suites share their enclosing class partition. Whole classes, all methods and lifecycle cycles retained.", "baseline_run": 41131475765, - "partition_count": 2, - "schema_version": 1, + "schema_version": 2, "services": { "account-service": { + "partition_count": 2, "tasks": { "integrationTest": { "classes": { @@ -1087,19 +1087,20 @@ } }, "game-session-service": { + "partition_count": 4, "tasks": { "crossServiceTest": { "classes": { "net.firedevops.firemud.gamesession.CommunicationWebSocketCrossServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 40.208696821319634 }, "net.firedevops.firemud.gamesession.GameSessionPingWebMvcTest": { - "partition": 2, + "partition": 1, "weight_seconds": 2.3997700272916997 }, "net.firedevops.firemud.gamesession.LookWebSocketCrossServiceTest": { - "partition": 2, + "partition": 1, "weight_seconds": 16.416050329105794 }, "net.firedevops.firemud.gamesession.MultiplayerLoadProofCrossServiceTest": { @@ -1122,15 +1123,15 @@ "integrationTest": { "classes": { "integration.net.firedevops.firemud.gamesession.repository.AccountInitialAdmissionSettlementPostgresIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 21.608676228722494 }, "integration.net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.8987596738878183 }, "integration.net.firedevops.firemud.gamesession.repository.CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 5.243976964291119 }, "integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest": { @@ -1146,11 +1147,11 @@ "weight_seconds": 43.40437759189563 }, "integration.net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 47.09916302582058 }, "integration.net.firedevops.firemud.gamesession.repository.CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 8.244691343699234 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest": { @@ -1158,43 +1159,43 @@ "weight_seconds": 16.976687065494872 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepositoryIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 10.822521113543948 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 10.740437860090609 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionAssociationReadIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 30.62848285186718 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 10.290538508884339 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 42.46301774849406 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 50.38457122100356 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 30.522501942345144 }, "integration.net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 11.954023176970347 }, "integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 11.960257348118699 }, "integration.net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 6.357815542797179 }, "net.firedevops.firemud.gamesession.GameSessionApplicationIntegrationTest": { @@ -1202,15 +1203,15 @@ "weight_seconds": 11.172673726376544 }, "net.firedevops.firemud.gamesession.GameSessionLoginIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 3.0703292905647435 }, "net.firedevops.firemud.gamesession.charactercreate.PlayerCreatedRosterOwnerCompositionIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 100.66004444691093 }, "net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClientMtlsIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 7.566205717053286 }, "net.firedevops.firemud.gamesession.controller.EffectiveSettingsControllerIntegrationTest": { @@ -1218,7 +1219,7 @@ "weight_seconds": 3.022533978427356 }, "net.firedevops.firemud.gamesession.controller.GameInstanceControllerTest": { - "partition": 1, + "partition": 4, "weight_seconds": 1.669718839234363 }, "net.firedevops.firemud.gamesession.controller.PingControllerTest": { @@ -1226,11 +1227,11 @@ "weight_seconds": 1.4951620470804283 }, "net.firedevops.firemud.gamesession.controller.SessionRoleControllerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 1.3871030805089448 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 14.014416741501611 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountAdmissionIntentMigrationPostgresIntegrationTest": { @@ -1238,11 +1239,11 @@ "weight_seconds": 2.0645496786301676 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 29.59776655533918 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 3.690629319826047 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryRepositoryIntegrationTest": { @@ -1250,7 +1251,7 @@ "weight_seconds": 28.914085786069602 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayDecisionRuntimeFenceIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 24.41093615990798 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest": { @@ -1258,43 +1259,43 @@ "weight_seconds": 171.72751748110628 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 25.57672616465033 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 15.909604770601472 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 19.655302602237988 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 10.038054577375968 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 12.939022218410406 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 2.8749919279162923 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 2.1320865327373446 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 20.31716377248832 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLocalCapacityIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 91.3160609240518 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 37.17851867173862 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPhysicalRetirementIntegrationTest": { @@ -1306,31 +1307,31 @@ "weight_seconds": 21.60140302904941 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayLegacyMigrationRepositoryIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 5.5930905485989895 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCandidateClosureLuaIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.31586467151664366 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 48.6140666148708 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.3065134147941114 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 118.43054930529631 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 44.52133325597586 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 4.50418865468635 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionLeaseOwnerIntegrationTest": { @@ -1338,27 +1339,27 @@ "weight_seconds": 40.48055132331722 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.31066952889301463 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 2.580946855418891 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferencePostgresIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 98.73160750501982 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 6.107409668338261 }, "net.firedevops.firemud.gamesession.repository.ExactScriptPatchBaseMigrationIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 2.7710890754437125 }, "net.firedevops.firemud.gamesession.repository.GameInstanceScriptPinMigrationIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 2.1061108196191993 }, "net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest": { @@ -1366,19 +1367,19 @@ "weight_seconds": 24.244691595951853 }, "net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 2.4365218904820045 }, "net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantHistoryPostgresIntegrationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 2.3596337796522953 }, "net.firedevops.firemud.gamesession.repository.GameSessionV2QuiescenceMigrationIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 1.9190856851685552 }, "net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerMigrationIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 3.9109033670679167 }, "net.firedevops.firemud.gamesession.repository.GameplayCommandAccountUuidMigrationIntegrationTest": { @@ -1386,11 +1387,11 @@ "weight_seconds": 2.6349763387046323 }, "net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 4.2007923254664155 }, "net.firedevops.firemud.gamesession.repository.PlayerCommandHistoryRepositoryIntegrationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 2.312877496039634 }, "net.firedevops.firemud.gamesession.repository.RemoteCommandCoordinatorRepositoryIntegrationTest": { @@ -1398,43 +1399,43 @@ "weight_seconds": 3.223066483699436 }, "net.firedevops.firemud.gamesession.repository.ResumeTranscriptEntryRepositoryIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 2.4936684593419236 }, "net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepositoryIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 2.4157413199874886 }, "net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 3.348788935191258 }, "net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRedisIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 1.4006104513303805 }, "net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerCasPostgresIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 3.6927073768754983 }, "net.firedevops.firemud.gamesession.service.InitialAdmissionBindPostgresIntegrationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 2.1622183599543927 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 15.746477292219522 }, "net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchPostgresIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 2.124813333064264 }, "net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceLifecycleIntegrationTest": { - "partition": 2, + "partition": 1, "weight_seconds": 5.75621802698094 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionGrpcServicePingIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.49353854924475565 }, "net.firedevops.firemud.gamesession.service.impl.TickQueueControlServiceRedisIntegrationTest": { @@ -1442,7 +1443,7 @@ "weight_seconds": 1.1429313771983818 }, "net.firedevops.firemud.gamesession.websocket.GameSessionWebSocketHandlerIntegrationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 36.787843946441726 } }, @@ -1461,19 +1462,19 @@ "test": { "classes": { "db.migration.V1__baselineTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.1223409044001297 }, "db.migration.V2__scope_gameplay_command_identityTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.008294298603398625 }, "db.migration.V4__retain_gameplay_command_script_patch_base_provenanceTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.CrossServiceAppHarnessTest": { - "partition": 1, + "partition": 2, "weight_seconds": 2.515246051480633 }, "net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperationTest": { @@ -1485,23 +1486,23 @@ "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.cache.RedisLookCacheServiceTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.4053838442411078 }, "net.firedevops.firemud.gamesession.cache.RedisScreenBufferServiceTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.235350722871436 }, "net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceGrpcServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.14929737486117522 }, "net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceMtlsTest": { - "partition": 2, + "partition": 1, "weight_seconds": 10.704829135011348 }, "net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 4.056948804387352 }, "net.firedevops.firemud.gamesession.client.AccountClientTest": { @@ -1525,7 +1526,7 @@ "weight_seconds": 7.6877780180251 }, "net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClientMtlsTest": { - "partition": 1, + "partition": 4, "weight_seconds": 7.442059421899416 }, "net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest": { @@ -1533,31 +1534,31 @@ "weight_seconds": 5.803935447728187 }, "net.firedevops.firemud.gamesession.client.CanonicalPreseededActorAssignmentClientMtlsTest": { - "partition": 2, + "partition": 4, "weight_seconds": 6.977578700109094 }, "net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClientMtlsTest": { - "partition": 2, + "partition": 4, "weight_seconds": 10.053726694644556 }, "net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClientTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.12026732974928007 }, "net.firedevops.firemud.gamesession.client.EntityManagementClientTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.0808694113831366 }, "net.firedevops.firemud.gamesession.client.GameDesignClientTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.11197303114588143 }, "net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClientTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.3068890483257491 }, "net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClientMtlsTest": { - "partition": 2, + "partition": 3, "weight_seconds": 7.880620460554118 }, "net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClientTest": { @@ -1565,39 +1566,39 @@ "weight_seconds": 0.7444132996550265 }, "net.firedevops.firemud.gamesession.client.GameLogicClientTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.2177253383392139 }, "net.firedevops.firemud.gamesession.client.GrpcAccountStartSessionAdmissionProtectionClientMtlsTest": { - "partition": 2, + "partition": 4, "weight_seconds": 22.16340265560655 }, "net.firedevops.firemud.gamesession.client.GrpcAccountStartSessionAdmissionProtectionClientTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.003110361976274484 }, "net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClientMtlsTest": { - "partition": 2, + "partition": 1, "weight_seconds": 7.4814573402655595 }, "net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClientTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.09434764661365935 }, "net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClientTest": { - "partition": 1, + "partition": 3, "weight_seconds": 6.367947752759294 }, "net.firedevops.firemud.gamesession.client.WorldManagementClientTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.011404660579673107 }, "net.firedevops.firemud.gamesession.command.text.ActionStateCommandHandlerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.07775904940686211 }, "net.firedevops.firemud.gamesession.command.text.ActivityTextCommandDispatchHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.05391294092209106 }, "net.firedevops.firemud.gamesession.command.text.AdmittedCommandDefinitionReaderTest": { @@ -1605,23 +1606,23 @@ "weight_seconds": 0.18765850590189387 }, "net.firedevops.firemud.gamesession.command.text.AdmittedTextCommandRegistryResolverTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.06946475080346348 }, "net.firedevops.firemud.gamesession.command.text.AfkCommandHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.09331085928823453 }, "net.firedevops.firemud.gamesession.command.text.AggregatingTextCommandRegistryTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.command.text.AuthoredActionCommandHandlerTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.AuthoredActionTextCommandDispatchHandlerTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.04769221696954209 }, "net.firedevops.firemud.gamesession.command.text.BuiltInTextCommandAliasResolverTest": { @@ -1629,15 +1630,15 @@ "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelectionTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.45929678516319883 }, "net.firedevops.firemud.gamesession.command.text.CommunicationCommandHandlerTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.20424710310869112 }, "net.firedevops.firemud.gamesession.command.text.ContainerCommandHandlerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.023846108484771044 }, "net.firedevops.firemud.gamesession.command.text.ContainerIdentitySupportTest": { @@ -1653,31 +1654,31 @@ "weight_seconds": 0.12648805370182903 }, "net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalogTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.09642122126450901 }, "net.firedevops.firemud.gamesession.command.text.HelpCommandHandlerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.008294298603398625 }, "net.firedevops.firemud.gamesession.command.text.HelpTextCommandDispatchHandlerTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.HistoryCommandHandlerTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.10056837056620833 }, "net.firedevops.firemud.gamesession.command.text.HistoryTextCommandDispatchHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.InventoryCommandHandlerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.015551809881372421 }, "net.firedevops.firemud.gamesession.command.text.ItemCommandHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.16899633404424697 }, "net.firedevops.firemud.gamesession.command.text.LoginCommandHandlerTest": { @@ -1685,11 +1686,11 @@ "weight_seconds": 0.560901943054832 }, "net.firedevops.firemud.gamesession.command.text.LogoutCommandHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.command.text.LookCommandHandlerTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.1316719903289532 }, "net.firedevops.firemud.gamesession.command.text.LookTextCommandDispatchHandlerTest": { @@ -1697,7 +1698,7 @@ "weight_seconds": 0.05806009022379038 }, "net.firedevops.firemud.gamesession.command.text.MoveCommandHandlerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.03628755638986898 }, "net.firedevops.firemud.gamesession.command.text.PlayCommandHandlerTest": { @@ -1705,19 +1706,19 @@ "weight_seconds": 0.22290927496633803 }, "net.firedevops.firemud.gamesession.command.text.PlayerCommandHistoryFlowTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.06842796347803866 }, "net.firedevops.firemud.gamesession.command.text.PlayerCommandHistoryRecorderTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.06013366487464004 }, "net.firedevops.firemud.gamesession.command.text.RegistryBackedTextCommandMetadataResolverTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.command.text.SessionResumptionFlowTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.49143719225136845 }, "net.firedevops.firemud.gamesession.command.text.StatusCommandHandlerTest": { @@ -1725,7 +1726,7 @@ "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.command.text.TextCommandDispatcherTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.TextCommandEffectDeclarationTest": { @@ -1733,27 +1734,27 @@ "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.command.text.TextCommandInterpreterCapabilityTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.05806009022379038 }, "net.firedevops.firemud.gamesession.command.text.TextCommandInterpreterDispatchSeamTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.09953158324078348 }, "net.firedevops.firemud.gamesession.command.text.TextCommandInterpreterTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.13581913963065248 }, "net.firedevops.firemud.gamesession.command.text.TextCommandParserTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.0331771944135945 }, "net.firedevops.firemud.gamesession.command.text.WhoCommandHandlerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.1824745692747697 }, "net.firedevops.firemud.gamesession.command.text.WorldsCommandHandlerTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.command.text.WorldsTextCommandDispatchHandlerTest": { @@ -1765,43 +1766,43 @@ "weight_seconds": 0.054949728247515886 }, "net.firedevops.firemud.gamesession.config.EffectiveReconnectionSettingsResolverTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.config.EffectiveSettingsResolverTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.004147149301699312 }, "net.firedevops.firemud.gamesession.controller.EffectiveSettingsControllerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.1731434833459463 }, "net.firedevops.firemud.gamesession.data.GameplayAdmissionPointerBootstrapInitializerTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.07879583673228693 }, "net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwnerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.22083570031548835 }, "net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapabilityTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.2218724876409132 }, "net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCoordinatorTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.16588597206797248 }, "net.firedevops.firemud.gamesession.data.TestDataSeederTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.10264194521705798 }, "net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResultTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.7298982770990788 }, "net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResultTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.006220723952548968 }, "net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshotTest": { @@ -1813,39 +1814,39 @@ "weight_seconds": 0.07464868743058761 }, "net.firedevops.firemud.gamesession.health.GameplayPathReadinessHealthIndicatorTest": { - "partition": 1, + "partition": 3, "weight_seconds": 2.4582227485822674 }, "net.firedevops.firemud.gamesession.health.PingHealthIndicatorTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.07361190010516279 }, "net.firedevops.firemud.gamesession.logging.GameSessionCommandLogSanitizerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.mapper.GameInstanceMapperTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.presentation.CommunicationOutputMapperTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.presentation.LookViewOutputTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.003110361976274484 }, "net.firedevops.firemud.gamesession.presentation.PlayerOutputTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.presentation.PromptBurstCoordinatorTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.004147149301699312 }, "net.firedevops.firemud.gamesession.presentation.PromptComposerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.presentation.SpeechPresentationNormalizerTest": { @@ -1853,19 +1854,19 @@ "weight_seconds": 0.0 }, "net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRendererTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.013478235230522766 }, "net.firedevops.firemud.gamesession.presentation.WorldsViewOutputTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.repository.AccountInitialAdmissionProtectionBindingRepositoryTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.9787272352010375 }, "net.firedevops.firemud.gamesession.repository.CanonicalCurrentOpenPointerSnapshotDigestTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.008294298603398625 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountAdmissionFenceIntentTest": { @@ -1877,7 +1878,7 @@ "weight_seconds": 1.2711012609708392 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountInitialBarrierValueTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountMemberRepairOwnerTest": { @@ -1885,15 +1886,15 @@ "weight_seconds": 0.037324343715293806 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAccountMemberRepairRedisOwnerTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.012441447905097935 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortOwnerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.4686278710920223 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionDecisionReadGrpcServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.7070889559397328 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventorySqlTest": { @@ -1901,39 +1902,39 @@ "weight_seconds": 0.01036787325424828 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayFreshNamespaceRedisReconcilerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.488326830275094 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.05702330289836555 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBootstrapAmbientTransactionTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.5588283684039823 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerMemberV2ValueCodecTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.0259196831356207 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPhysicalFieldSetCodecTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.014515022555947594 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerRedisKeysTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.004147149301699312 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayLegacyMigrationOwnerTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.11923054242385522 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayLegacyRedisSourceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.011404660579673107 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayMigrationDriverMainTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.12441447905097937 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayMigrationDriverProtocolTest": { @@ -1945,15 +1946,15 @@ "weight_seconds": 0.2260196369426125 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewAuthenticatedSessionTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.3535444779698664 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCandidateTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.014515022555947594 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionReadRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.015551809881372421 }, "net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionRedisKeysTest": { @@ -1965,23 +1966,23 @@ "weight_seconds": 0.0 }, "net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepositoryTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.22083570031548835 }, "net.firedevops.firemud.gamesession.repository.CreateCanonicalRealmCatalogRequestSnapshotBoundsTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.01036787325424828 }, "net.firedevops.firemud.gamesession.repository.GameInstanceRepositoryOperationKindValidationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.repository.GameInstanceRepositoryTest": { - "partition": 2, + "partition": 4, "weight_seconds": 1.3250142018929303 }, "net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepositoryTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.066354388827189 }, "net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigestTest": { @@ -1989,43 +1990,43 @@ "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.004147149301699312 }, "net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.003110361976274484 }, "net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepositoryTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepositoryTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.6324402685091451 }, "net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepositoryTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.25401289472908284 }, "net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepositoryTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.01762538453222208 }, "net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepositoryTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.015551809881372421 }, "net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.07672226208143727 }, "net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewFinalAdmissionReadWorkloadGuardTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.security.GameSessionGrpcAuthInterceptorTest": { @@ -2033,43 +2034,43 @@ "weight_seconds": 0.012441447905097935 }, "net.firedevops.firemud.gamesession.security.ProtectedGameSessionLoginGrpcInterceptorTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.07050153812888832 }, "net.firedevops.firemud.gamesession.service.AccountInitialAdmissionSettlementReadServiceTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.1181937550984304 }, "net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceRetentionServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.1814377819493449 }, "net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolverTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.41575171749535605 }, "net.firedevops.firemud.gamesession.service.CommunicationRecipientDeliveryServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.3141465596037229 }, "net.firedevops.firemud.gamesession.service.DurableResumeTranscriptExpiryJobTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.07361190010516279 }, "net.firedevops.firemud.gamesession.service.DurableScreenBufferServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.023846108484771044 }, "net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolutionTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.011404660579673107 }, "net.firedevops.firemud.gamesession.service.FirstPartyConnectContextServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.05080257894581658 }, "net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.34525017936646774 }, "net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinatorTest": { @@ -2077,15 +2078,15 @@ "weight_seconds": 0.14100307625777664 }, "net.firedevops.firemud.gamesession.service.GameplayPresenceActivityResolverTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwnerTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.30585226100032425 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClientTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.17210669602052148 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextStateTest": { @@ -2093,7 +2094,7 @@ "weight_seconds": 0.02073574650849656 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwnerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.20424710310869112 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisAttemptClosureTest": { @@ -2101,27 +2102,27 @@ "weight_seconds": 0.06428081417633934 }, "net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBindingTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.006220723952548968 }, "net.firedevops.firemud.gamesession.service.PlayerCommandHistoryRetentionSweepJobTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.06842796347803866 }, "net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.PlayerOutputDeliveryServiceTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.13685592695607732 }, "net.firedevops.firemud.gamesession.service.PositiveLongParsingTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.service.ReplayableScreenBufferEntriesTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.0404347056915683 }, "net.firedevops.firemud.gamesession.service.ResumeTranscriptEntryCanonicalizerTest": { @@ -2129,15 +2130,15 @@ "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.ScriptPinTupleCoherenceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.004147149301699312 }, "net.firedevops.firemud.gamesession.service.SessionAuthenticationServiceTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.service.SessionContextTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.SessionIdParsingTest": { @@ -2145,7 +2146,7 @@ "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.service.impl.AccountInitialAdmissionSettlementReadGrpcServiceTest": { @@ -2153,15 +2154,15 @@ "weight_seconds": 7.3777786077230765 }, "net.firedevops.firemud.gamesession.service.impl.AccountPresenceQueryServiceImplTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.013478235230522766 }, "net.firedevops.firemud.gamesession.service.impl.AuthenticatedCanonicalInitialAdmissionWorldVerifierTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.295484387746076 }, "net.firedevops.firemud.gamesession.service.impl.AutomationGameplayCommandAdmissionSupportTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.7070889559397328 }, "net.firedevops.firemud.gamesession.service.impl.AutomationScriptEventPublisherTest": { @@ -2169,11 +2170,11 @@ "weight_seconds": 0.05080257894581658 }, "net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.08294298603398624 }, "net.firedevops.firemud.gamesession.service.impl.CommandServiceImplTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.09849479591535866 }, "net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityServiceTest": { @@ -2181,23 +2182,23 @@ "weight_seconds": 0.09123728463738486 }, "net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayCommandRecoveryServiceTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.1596652481154235 }, "net.firedevops.firemud.gamesession.service.impl.DefaultDurableGameplayCommandExecutionServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.4655175091157478 }, "net.firedevops.firemud.gamesession.service.impl.DefaultDurableRemoteFollowupExecutionServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.07361190010516279 }, "net.firedevops.firemud.gamesession.service.impl.DefaultGameplayPresenceLifecycleServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.003110361976274484 }, "net.firedevops.firemud.gamesession.service.impl.GameAuthoredHelpReaderImplTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceImplTest": { @@ -2205,11 +2206,11 @@ "weight_seconds": 0.548460495149734 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionAdmissionPointerControlPlaneServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.013478235230522766 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionControlPlaneGrpcServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.8791956519602542 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionFixtureLaunchAssociationReadGrpcServiceTest": { @@ -2217,15 +2218,15 @@ "weight_seconds": 0.5723066036345051 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionGrpcServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.5432765585226099 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionOperatorControlPlaneServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.022809321159346214 }, "net.firedevops.firemud.gamesession.service.impl.GameSessionRuntimeControlPlaneReadServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.015551809881372421 }, "net.firedevops.firemud.gamesession.service.impl.GameplayCharacterIdParserTest": { @@ -2233,11 +2234,11 @@ "weight_seconds": 0.0 }, "net.firedevops.firemud.gamesession.service.impl.GameplayCommandExecutionFenceServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.service.impl.GameplayPresenceRoleClassifierTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.17418027067137112 }, "net.firedevops.firemud.gamesession.service.impl.InMemoryActiveTransportSessionRegistryTest": { @@ -2249,15 +2250,15 @@ "weight_seconds": 0.019698959183071733 }, "net.firedevops.firemud.gamesession.service.impl.InitialAdmissionBindServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.14203986358320145 }, "net.firedevops.firemud.gamesession.service.impl.InstanceCutoverCompatibilityServiceImplTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.impl.IpConnectionLimiterImplTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.service.impl.PingServiceImplTest": { @@ -2273,35 +2274,35 @@ "weight_seconds": 0.003110361976274484 }, "net.firedevops.firemud.gamesession.service.impl.RedisFirstPartyConnectContextRegistryTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.014515022555947594 }, "net.firedevops.firemud.gamesession.service.impl.RedisGameplayPresenceServiceTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.1295984156781035 }, "net.firedevops.firemud.gamesession.service.impl.RedisMovementEffectIdempotencyServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.006220723952548968 }, "net.firedevops.firemud.gamesession.service.impl.RedisSessionContextServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.012441447905097935 }, "net.firedevops.firemud.gamesession.service.impl.RemoteFollowupDrainServiceImplTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.00518393662712414 }, "net.firedevops.firemud.gamesession.service.impl.RemoteFollowupRuntimeServiceImplTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.09123728463738486 }, "net.firedevops.firemud.gamesession.service.impl.ScriptPatchPublicationLinkResolverTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.impl.SessionRateLimiterImplTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.001036787325424828 }, "net.firedevops.firemud.gamesession.service.impl.TcpProxyServiceImplTest": { @@ -2309,11 +2310,11 @@ "weight_seconds": 0.12441447905097937 }, "net.firedevops.firemud.gamesession.service.impl.TickBatchExecutionServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.820098774411039 }, "net.firedevops.firemud.gamesession.service.impl.TickQueueControlServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.235350722871436 }, "net.firedevops.firemud.gamesession.service.impl.TickRedisScriptTest": { @@ -2321,23 +2322,23 @@ "weight_seconds": 3.266916862413633 }, "net.firedevops.firemud.gamesession.service.impl.TickRuntimeProgressServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.009331085928823452 }, "net.firedevops.firemud.gamesession.service.impl.TickSchedulerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.014515022555947594 }, "net.firedevops.firemud.gamesession.service.impl.TickServiceImplTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.8003998152279672 }, "net.firedevops.firemud.gamesession.service.impl.TickStageScriptTest": { - "partition": 1, + "partition": 3, "weight_seconds": 2.053875691666584 }, "net.firedevops.firemud.gamesession.service.impl.TickStagingServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.08812692266111039 }, "net.firedevops.firemud.gamesession.service.impl.TriggerScriptEventRequestFactoryTest": { @@ -2345,15 +2346,15 @@ "weight_seconds": 0.002073574650849656 }, "net.firedevops.firemud.gamesession.service.impl.VersionUpgradePreparationServiceImplTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.09538443393908418 }, "net.firedevops.firemud.gamesession.test.ChatTestFixturesTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.007257511277973797 }, "net.firedevops.firemud.gamesession.test.GameInstanceTestFixturesTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.10056837056620833 }, "net.firedevops.firemud.gamesession.test.GameplayCommandTestFixturesTest": { @@ -2365,15 +2366,15 @@ "weight_seconds": 0.009331085928823452 }, "net.firedevops.firemud.gamesession.test.stubs.EntityManagementStubServerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.08605334801026074 }, "net.firedevops.firemud.gamesession.test.stubs.GameDesignStubServerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.0404347056915683 }, "net.firedevops.firemud.gamesession.test.stubs.WorldManagementStubServerTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.054949728247515886 }, "net.firedevops.firemud.gamesession.testsupport.GameplayStructuredCommandAssertionsTest": { @@ -2385,23 +2386,23 @@ "weight_seconds": 0.0 }, "net.firedevops.firemud.gamesession.websocket.GameSessionWebSocketHandlerTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.21461497636293939 }, "net.firedevops.firemud.gamesession.websocket.GameSessionWebSocketHandshakeInterceptorTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.01762538453222208 }, "net.firedevops.firemud.gamesession.websocket.WebSocketOutputProjectorTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.06531760150176416 }, "unit.net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentityTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.001036787325424828 }, "unit.net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClientTest": { - "partition": 1, + "partition": 4, "weight_seconds": 8.037175346693267 }, "unit.net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClientMtlsTest": { @@ -2409,59 +2410,59 @@ "weight_seconds": 7.259584852624646 }, "unit.net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClientTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.16381239741712283 }, "unit.net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClientTest": { - "partition": 2, + "partition": 3, "weight_seconds": 1.5614017120897912 }, "unit.net.firedevops.firemud.gamesession.client.CanonicalPreseededActorAssignmentClientTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.04976579162039174 }, "unit.net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfigurationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.2063206777595408 }, "unit.net.firedevops.firemud.gamesession.config.CanonicalInitialAdmissionOwnerConfigurationTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.17003312136967183 }, "unit.net.firedevops.firemud.gamesession.config.CanonicalPlayerRouteReadConfigurationTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.2000999538069918 }, "unit.net.firedevops.firemud.gamesession.config.GameLogicPropertiesTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.1482605875357504 }, "unit.net.firedevops.firemud.gamesession.config.GameSessionGrpcRequestByteConfigurationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.6749485488515631 }, "unit.net.firedevops.firemud.gamesession.config.GameSessionStartSessionOperatorAuthorizationConfigurationTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.17210669602052148 }, "unit.net.firedevops.firemud.gamesession.config.InternalGrpcClientAuthConfigTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.038361131040718636 }, "unit.net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociationTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.00518393662712414 }, "unit.net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequestTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.003110361976274484 }, "unit.net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.004147149301699312 }, "unit.net.firedevops.firemud.gamesession.repository.CanonicalHumanRuntimeCompletionRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.1772906326476456 }, "unit.net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepositoryTest": { @@ -2473,23 +2474,23 @@ "weight_seconds": 0.0 }, "unit.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.001036787325424828 }, "unit.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.002073574650849656 }, "unit.net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepositoryTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.09434764661365935 }, "unit.net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepositoryTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.006220723952548968 }, "unit.net.firedevops.firemud.gamesession.security.CanonicalGameplayRosterOwnerReadInterceptorChainTest": { - "partition": 1, + "partition": 2, "weight_seconds": 1.121803886109664 }, "unit.net.firedevops.firemud.gamesession.security.PreseededActorAssignmentOwnerReadInterceptorChainTest": { @@ -2497,35 +2498,35 @@ "weight_seconds": 0.10471551986790764 }, "unit.net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwnerTest": { - "partition": 1, + "partition": 2, "weight_seconds": 1.6547125713780257 }, "unit.net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferencePolicyTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.006220723952548968 }, "unit.net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 15.8224113733083 }, "unit.net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.011404660579673107 }, "unit.net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.2871900891426774 }, "unit.net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.3670227132003891 }, "unit.net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshotsTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.003110361976274484 }, "unit.net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest": { - "partition": 2, + "partition": 4, "weight_seconds": 0.09331085928823453 }, "unit.net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapterTest": { @@ -2533,19 +2534,19 @@ "weight_seconds": 0.22394606229176287 }, "unit.net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterReferenceGrpcMtlsTest": { - "partition": 2, + "partition": 1, "weight_seconds": 9.076036246768945 }, "unit.net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionHoldPreparationTest": { - "partition": 1, + "partition": 2, "weight_seconds": 0.012441447905097935 }, "unit.net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionOwnerReadGrpcServiceTest": { - "partition": 2, + "partition": 1, "weight_seconds": 0.01762538453222208 }, "unit.net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionServiceTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.003110361976274484 }, "unit.net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest": { @@ -2553,7 +2554,7 @@ "weight_seconds": 11.93549569029062 }, "unit.net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.5806009022379037 }, "unit.net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest": { @@ -2561,15 +2562,15 @@ "weight_seconds": 0.003110361976274484 }, "unit.net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcServiceTest": { - "partition": 2, + "partition": 3, "weight_seconds": 0.037324343715293806 }, "unit.net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadWorkloadGuardTest": { - "partition": 1, + "partition": 3, "weight_seconds": 0.001036787325424828 }, "unit.net.firedevops.firemud.gamesession.support.MutableDefaultDemoCatalogTest": { - "partition": 1, + "partition": 4, "weight_seconds": 0.003110361976274484 } }, From 4fb3446c5efd055cc85bc00482f95c12885a224d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:39:54 +1300 Subject: [PATCH 07/11] Fix nondispatched script patch failure receipts and readiness refusal --- .../api-contracts.md | 2 - ...ame-authoring-publishing-and-activation.md | 4 +- .../impl/AutomationScriptingGrpcService.java | 6 +- .../AutomationScriptingGrpcServiceTest.java | 47 +++++++++- .../service/impl/VersionServiceImpl.java | 18 ++-- .../service/impl/VersionServiceImplTest.java | 90 +++++++++++++++++++ 6 files changed, 149 insertions(+), 18 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 956486ca9b..3f66b51be2 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -285,5 +285,3 @@ The selected-empty service also requires the complete incoming publication reque For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission. **Current status:** `GetDraftDesignDigest` invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before returning `UNSUPPORTED_SCOPE` for either selector. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The selected-empty schema-6 primitive remains unregistered; exact version mapping and the base-bound patch manifest are still required before a publication digest can be returned. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. - -The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The guard requires the exact authenticated Game Design workload mTLS peer and denies account or role-bearing context; role-free internal identity alone is not authorization or a substitute for that peer. Live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its existing live full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. 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 5896a922bd..d59caf5070 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 @@ -427,7 +427,7 @@ The local receiving preparation preserves the stronger public full-publication a New patched launch selection already fails closed. The receiving correction additionally refuses a retained patched descriptor after exact immutable request/source/result verification, for both replay and readback; it preserves valid unpatched resolution. No manifest, readiness receipt, digest, pin epoch or cleanup/release protocol is invented. Canonical semantics remain in [Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). -Focused regression sources cover manifest refusal and retained failure/tuple custody, prior PENDING reconciliation, concurrent terminal outcomes, response rejection and empty-handler dispatch, and retained patched descriptor replay/readback. Validation: NONE; tests, compilation, formatting, static checks and documentation gates are deferred to the lane orchestrator. These authored regressions are not executed proof. Complete manifest production, readiness-owner convergence, production Temporal execution, and live player activation remain open. +Focused regression sources cover manifest refusal and retained failure/tuple custody, prior PENDING reconciliation, concurrent terminal outcomes, response rejection and empty-handler dispatch, and retained patched descriptor replay/readback. The original R1420 attribution records 178 selected Game Design cases (156 unit and 22 actual PostgreSQL/application) alongside 50 Automation units; see [Validation and Proof](#validation-and-proof) for the recorded source and controlled-participant limits. That prior proof does not establish execution of these receiving edits or production authority. Complete manifest production, readiness-owner convergence, production Temporal execution, and live player activation remain open. ### Published Asset Lifecycle @@ -518,4 +518,6 @@ No competing current authority is recorded for settings, versioned release bundl R1420 local publication-containment proof passes 178 selected Game Design cases: 156 unit cases and 22 actual PostgreSQL/application cases, alongside 50 Automation units in the combined gate. The real patch owner records a manifest-unavailable terminal failure while retaining its canonical DRAFT tuple; exact retry preserves complete attempt/candidate rows and `xmin`, a genuine pre-existing PENDING original remains unchanged without redispatch, and the direct owner transaction rolls back its Draft/attempt writes together. Launch-descriptor SQL and current full-version offline transaction controls also pass. Participant gates are controlled collaborators, not genuine publication or manifest authority. Enabled affected static analysis, full formatting, both service packages and documentation checks pass; fresh canonical image-lane held smoke builds all eleven applications from carried source `eaee2ed9af91c2a6ad217df0b00d1bea16dcbb5f` and passes direct backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial. Authenticated run-owned teardown and independent exact-project queries find no containers, networks or volumes. Successful public admission and production publication/activation remain unproved. Existing full-publication authorization refusal, production manifest/readiness, Account/World source authority, recovery and activation holds remain. +A later focused local correction qualifies retryable dependency failures after the script-patch participant gate as pre-dispatch because this receiving path never dispatches readiness. It passes 60 Version Service units, 26 Automation gRPC units and 12 actual PostgreSQL/application publication-owner cases, with no failures, errors or skips. The controlled unit histories verify the existing retryable FAILED receipt and exact replay without repeated participant work; genuine pre-existing PENDING originals and uncertain receipt persistence remain held for owner reconciliation. The Automation adapter separately distinguishes an unverifiable empty handler manifest from a non-current nonempty request. Enabled affected Checkstyle and SpotBugs, full formatting and documentation checks pass. This focused proof does not establish manifest production, positive readiness, real Temporal execution or activation; fresh packaged runtime and current remote CI remain separate qualifications. + The same coherent #2856 receiving boundary includes the remaining compatible Entity mutation/crafting containment and direct World terminal-request proof. Their detailed qualification stays with [Gameplay Rules](./gameplay-rules-entities-and-effects.md#validation-and-proof) and [World Runtime](./world-runtime-and-movement.md#validation-and-proof). Together the separate R1420 and R1422 gates pass 345 selected cases: 323 units and 22 actual PostgreSQL/application cases, with their original source attribution and controlled-input limits. After receiving current credential/audit parents and their review corrections, fresh canonical image-lane held smoke builds all eleven applications from `4f13634c416dbc16f8c2d29776e38e7f7038b2fc` and passes backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial. Run-owned teardown and independent exact-project checks find no containers, networks or volumes. This qualifies the combined local runtime, not a complete service suite, successful public admission, positive publication or production authority. diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java index 76beb2f4bf..081120f25d 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java @@ -500,13 +500,17 @@ public void notifyScriptVersionUpdate( request.getAffectedScriptsList()); response.setSuccess(readinessAccepted); if (!readinessAccepted) { + String errorMessage = + request.getAffectedScriptsCount() == 0 + ? "zero_handler_manifest_unverifiable" + : "patch_readiness_not_current"; response.setError( GrpcAppErrors.error( meterRegistry, logger, "NotifyScriptVersionUpdate", "FAILED_PRECONDITION", - "patch_readiness_not_current")); + errorMessage)); } } catch (IllegalArgumentException ex) { response diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java index 94c6a3b79b..626b4a1a75 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java @@ -783,10 +783,55 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); - assertEquals("patch_readiness_not_current", ref.get().getError().getMessage()); + assertEquals("zero_handler_manifest_unverifiable", ref.get().getError().getMessage()); Mockito.verify(versionService).notifyUpdate("1", 1L, "patch-1", List.of()); } + @Test + void notifyScriptVersionUpdateKeepsGenericReadinessFailureForNonEmptyAffectedScripts() { + ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); + Mockito.when(versionService.notifyUpdate("1", 1L, "patch-1", List.of("guard-script"))) + .thenReturn(false); + AutomationScriptingGrpcService service = + new AutomationScriptingGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(ScriptDefinitionService.class), + versionService, + Mockito.mock(ScriptScheduleInstanceService.class), + Mockito.mock(ScriptEventIngressService.class), + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(NpcFormationService.class), + new SimpleMeterRegistry(), + ""); + AtomicReference response = new AtomicReference<>(); + + service.notifyScriptVersionUpdate( + NotifyScriptVersionUpdateRequest.newBuilder() + .setTenantId("1") + .setBaseVersionId(1L) + .setScriptPatchVersion("patch-1") + .addAffectedScripts("guard-script") + .build(), + new StreamObserver<>() { + @Override + public void onNext(NotifyScriptVersionUpdateResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(response.get()); + assertFalse(response.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", response.get().getError().getCode()); + assertEquals("patch_readiness_not_current", response.get().getError().getMessage()); + Mockito.verify(versionService).notifyUpdate("1", 1L, "patch-1", List.of("guard-script")); + } + @Test void notifyScriptVersionUpdateMapsUnavailableBaseVersionArgumentToFailedPreconditionAppError() { ScriptVersionService versionService = Mockito.mock(ScriptVersionService.class); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 17b6084ea4..8c9df9b9c0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -182,13 +182,11 @@ public VersionDto publishScriptPatchVersion( "SCRIPT_PATCH_MANIFEST_UNAVAILABLE: the prior publish attempt may have dispatched readiness without a verifiable affected-script manifest")); } - boolean participantGatePassed = false; try { List participantDigests = publishGateService.collectScriptPatchParticipantDigests( reservation.versionDto(), patchBinding.publishRequestId(), publishWorkflowId); publishGateService.assertGatePassed(reservation.versionDto(), participantDigests); - participantGatePassed = true; recordedParticipantDigestService.assertMatchesRecordedDigests( tenantId, PublishType.SCRIPT_PATCH, participantDigests); throw new ScriptPatchPublishFailureException( @@ -208,19 +206,13 @@ public VersionDto publishScriptPatchVersion( } boolean retryableParticipantDependencyFailure = PublicationFailureClassifier.isRetryableParticipantDependencyFailure(operationFailure); - boolean retryablePreDispatchParticipantFailure = - !participantGatePassed && retryableParticipantDependencyFailure; - if (retryableParticipantDependencyFailure && !retryablePreDispatchParticipantFailure) { - throw new IllegalStateException( - "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED: participant dependency is temporarily unavailable; retry exact publish request", - operationFailure); - } + // This newly reserved path never dispatches readiness, even after the participant gate. String failureCode = - retryablePreDispatchParticipantFailure + retryableParticipantDependencyFailure ? RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE : publishFailureCode(operationFailure); String failureMessage = - retryablePreDispatchParticipantFailure + retryableParticipantDependencyFailure ? retryableParticipantDependencyFailureMessage() : publishFailureMessage(operationFailure); ScriptPatchFinalization failure; @@ -242,7 +234,7 @@ public VersionDto publishScriptPatchVersion( if (failure.status() == PublishAttemptStatus.FAILED) { if (Objects.equals(failure.failureCode(), failureCode) && Objects.equals(failure.failureMessage(), failureMessage)) { - if (retryablePreDispatchParticipantFailure) { + if (retryableParticipantDependencyFailure) { throw new ScriptPatchPublishFailureException( failure.failureCode(), failure.failureMessage(), operationFailure); } @@ -458,7 +450,7 @@ private ScriptPatchPublishFailureException pendingScriptPatchReconciliation( return new ScriptPatchPublishFailureException( errorCode, errorCode - + ": script-patch publication outcome is unknown; retry the exact publish request", + + ": script-patch publication outcome is unknown; owner reconciliation of the original attempt is required before publication can progress", cause); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 8ddccebd1c..15f28beb37 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -667,6 +667,8 @@ void sameStableScriptPatchIdKeepsPriorPendingAttemptForReconciliation() { "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); assertEquals(PublishAttemptPendingReconciliationException.ERROR_CODE, thrown.failureCode()); + assertTrue( + thrown.getMessage().contains("owner reconciliation of the original attempt is required")); assertTrue(thrown.getCause().getMessage().contains("SCRIPT_PATCH_MANIFEST_UNAVAILABLE")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); @@ -808,6 +810,94 @@ void transientPreDispatchFailureRetainsCanonicalTupleAndReplaysFailure(Status.Co .notifyScriptVersionUpdate(any(), any(), any(), any()); } + @ParameterizedTest + @EnumSource( + value = Status.Code.class, + names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void transientPostGateFailureRecordsFailedReceiptAndReplaysWithoutRecollection( + Status.Code statusCode) { + Game game = new Game(); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); + Version draft = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "original notes"); + PublishAttempt attempt = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); + when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + .thenReturn(Optional.empty()); + when(versionRepository.save(any(Version.class))).thenReturn(draft); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draft)); + when(publishAttemptService.findByPublishWorkflowId(binding.derivedWorkflowIdentity())) + .thenReturn(Optional.empty(), Optional.of(attempt)); + List digests = List.of(); + when(publishGateService.collectScriptPatchParticipantDigests(any(), any(), any())) + .thenReturn(digests); + StatusRuntimeException dependencyFailure = + new StatusRuntimeException(Status.fromCode(statusCode)); + doThrow(dependencyFailure) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests("tenant-1", PublishType.SCRIPT_PATCH, digests); + // Model the receipt owner's retained result; replay must read it, not repeat participant work. + doAnswer( + invocation -> { + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode(invocation.getArgument(1)); + attempt.setFailureMessage(invocation.getArgument(2)); + return null; + }) + .when(publishAttemptService) + .markScriptPatchFailed(any(String.class), any(String.class), any(String.class)); + + ScriptPatchPublishFailureException first = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "original notes", PUBLISH_REQUEST_ID)); + + assertEquals(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); + assertEquals(dependencyFailure, first.getCause()); + assertEquals(PublishAttemptStatus.FAILED, attempt.getStatus()); + assertEquals(first.failureCode(), attempt.getFailureCode()); + assertEquals(first.getMessage(), attempt.getFailureMessage()); + assertTrue(first.getMessage().contains("exact retries replay this failed receipt")); + ScriptPatchPublishFailureException replay = + assertThrows( + ScriptPatchPublishFailureException.class, + () -> + service.publishScriptPatchVersion( + "tenant-1", 3L, "patch-2", "changed notes", PUBLISH_REQUEST_ID)); + + assertEquals(first.failureCode(), replay.failureCode()); + assertEquals(first.getMessage(), replay.getMessage()); + assertEquals(binding.requestDigest(), attempt.getRequestDigest()); + assertEquals(11L, attempt.getVersionId()); + assertEquals(VersionLifecycleState.DRAFT, draft.getVersionState()); + assertEquals(3L, draft.getBaseVersionId()); + assertEquals("patch-2", draft.getScriptPatchVersion()); + assertEquals("original notes", draft.getNotes()); + verify(publishAttemptService, times(3)).executeScriptPatchTransaction(any()); + verify(publishAttemptService) + .markScriptPatchFailed( + binding.derivedWorkflowIdentity(), first.failureCode(), first.getMessage()); + verify(publishAttemptService) + .createScriptPatchAttempt( + any(), + org.mockito.ArgumentMatchers.eq(binding.derivedWorkflowIdentity()), + org.mockito.ArgumentMatchers.eq(3L), + org.mockito.ArgumentMatchers.eq(binding.requestDigest())); + verify(publishGateService).collectScriptPatchParticipantDigests(any(), any(), any()); + verify(publishGateService).assertGatePassed(any(), org.mockito.ArgumentMatchers.eq(digests)); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests("tenant-1", PublishType.SCRIPT_PATCH, digests); + verify(versionRepository).save(any(Version.class)); + verify(versionRepository, org.mockito.Mockito.never()).delete(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .markScriptPatchSucceeded(any(String.class)); + org.mockito.Mockito.verifyNoInteractions(scriptingClient); + } + @Test void pendingNonDraftCandidateRemainsHeldForReconciliation() { Game game = new Game(); From c925b3ddcb4348e88e5165b62b6007b8ccdecc11 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:55:42 +1300 Subject: [PATCH 08/11] Align Automation status with predispatch publication containment --- .../automation-scripting-service/api-contracts.md | 4 ++-- .../automation-scripting-service/runtime-and-data.md | 8 ++++---- .../automation-and-scheduler-runtime.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 3f66b51be2..6a821307e7 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -25,7 +25,7 @@ Target formation control-plane behavior eliminates unauthenticated service-local - `GetScriptBreakerStatus` and `ListScriptBreakerEvents` are target-state reads for the exact `(tenantId, gameInstanceId, scriptPatchVersion, scriptPinEpoch, scriptId)` core-script breaker identity, and `ResetScriptBreaker` is its target operator mutation. The current proto/implementation has no authoritative breaker status/history surface, monotonic breaker revision, reset mutation, stored request result, or reset evidence. They are distinct from `GetScriptPatchStatus` tenant readiness and `GetScriptStatus` pre-DSL work states; do not introduce or infer a `scriptVersionId`. - Target pre-DSL recovery permits rebuilding `PENDING_EVALUATION` and only an `EVALUATING` row whose owner proves the lease stale or explicitly releases ownership through one fenced compare-and-set covering the status, owner, freshness, and fence transition; unresolved, ambiguous, and non-stale rows remain excluded. The callable `rebuildPendingWorkItemIndex` remains an unsafe helper with no stale, owner, or compare-and-set reconciliation gate, so current queue reset/resume is unavailable and must fail closed; no live scheduled rebuild invokes it, and a non-atomic status preflight cannot authorize recovery. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). It does not implement target `PENDING`/`INDEXED` evaluated-descriptor rebuild because the separate descriptor status layer is not currently persisted; these pointers are not evaluated-command queue entries or descriptor replay evidence. - For a non-empty `NotifyScriptVersionUpdate` notification, the current path validates and stages patches through `PENDING_VALIDATION -> ONLOAD_RUNNING -> READY/FAILED/SUPERSEDED`; running instances reload only after a later pin change to that tenant-`READY` patch. -- In the current normal Game Design integration, `affectedScripts` is empty. Automation now returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and does not create readiness state or synthetic handler work. This is fail-closed containment, not the accepted terminal outcome: for an identifiable tenant/patch without verifiable zero-handler proof, ADR 0115 requires one durable `FAILED` readiness record with normal status/audit evidence and no DSL retry. That durable failure is not implemented in the current readiness owner, so the empty notification remains a readiness and publication blocker. An unidentifiable malformed notification may fail at transport/validation without fabricating a patch identity. For non-empty notifications, the readiness boolean is propagated to the RPC response; `success=true` means the owner accepted the current readiness operation, not that all handlers reached `READY`. +- New Game Design patch-publication attempts without an owner-verified affected-handler manifest fail with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification; a pre-existing `PENDING` attempt may already have dispatched and requires owner reconciliation, not redispatch. See [Game Design Version Control](../game-design-service/version-control.md#script-patch-versions-and-runtime-behavior) and the [patch-containment tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). If an empty `NotifyScriptVersionUpdate` request reaches this receiver, it returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; this defensive response is not positive readiness. For an identifiable patch without verifiable zero-handler proof, the durable `FAILED` status/audit required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) remains unimplemented. An unidentifiable malformed notification may fail validation without fabricating a patch identity. For non-empty notifications, the readiness boolean is propagated to the RPC response; `success=true` means the owner accepted the current readiness operation, not that all handlers reached `READY`. - The current `ListScriptHandoffEvents` proto/client reads handoff rows using `workItemId`/persisted `outboxWorkItemId`, `gameSessionCommandId`, `automationDispatchId`, and the currently supported scope, remote, provenance, routing, target, and source fields. The target complete Command-Handoff Identity and complete evaluated-descriptor semantics remain target-only end-to-end; locally stored ordinal/text/target values do not establish that target contract. The current proto/client exposes no `bindingId` request filter, and target response metadata remains target-state follow-through rather than a claimed live field. - `GetAutomationPinConvergence` is currently served from a durable Automation-owned `script_patch_pin_projections` view keyed by `(tenantId, gameInstanceId)` and returns freshness flags (`projectionAsOfMs`, `projectionLagMs`, `isProjectionStale`) so temporary Game Session read failures do not collapse operator visibility into raw pass-through coupling. - Signer/component-policy enforcement is live on the Automation runtime side. The current control-plane surface exposes `GetPluginStatus`, `ListPluginRuntimeEvents`, and `GetPluginPolicyConvergence`, and scheduled reconciliation disables enabled plugins when current publication metadata becomes fail-closed. The separate propagation-event families `SignerPolicyVersionObserved` and `SignerRevocationApplied` remain target-state follow-through rather than a shipped API family. @@ -63,7 +63,7 @@ curl http://localhost:8080/ping - `UpdateScript` – bootstrap/dev-only script upload path that replaces the script definition and its event bindings for the `(tenantId, version, name)` tuple in one operation. This is the stable definition identity enforced by the `scripts` table; it is distinct from runtime patch/script identity `(tenantId, scriptPatchVersion, scriptId)`. The definition write uses one PostgreSQL upsert, so an exact retry reuses the same retained row/ID and concurrent retries cannot insert duplicates; changed input on an existing tuple replaces the definition and bindings atomically rather than creating a second definition or a request-ID conflict. v1 has no separate request ID for this path; the current response reports success, not the row ID. - `GetScriptStatus` – queries durable queued work (`PENDING_EVALUATION`) and active evaluation work (`EVALUATING`) in the script work-item outbox. - `GetScriptBreakerStatus` – **target-state read:** returns the exact core-script breaker tuple, `breakerState`, bounded `breakerReason`, monotonic `breakerRevision`, monotonic `breakerSampleGeneration`, policy/window/classified-sample evidence, audited reset evidence when applicable, and timestamps. `ListScriptBreakerEvents` is the corresponding bounded history read with optional tuple/state/time selectors and explicit `TRIPPED`/`RESET` transitions. `ResetScriptBreaker` is the target operator mutation: it selects the same exact tuple, requires expected disabled state/revision plus bounded validation evidence, and atomically resets through the revision-fenced owner history contract while advancing the sample generation so pre-reset samples remain history-only. The current proto/implementation exposes none of these surfaces; canonical field, authorization, idempotency, concurrency, and reset semantics live in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md#getscriptbreakerstatus). -- `NotifyScriptVersionUpdate` – production rollout notification to Automation & Scripting that a Game Design-published `script_patch_version` is available for tenant-readiness ingestion. The current empty-list path returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and creates no readiness row; ADR 0115's required durable `FAILED` record with status/audit evidence remains unimplemented. +- `NotifyScriptVersionUpdate` – production rollout notification to Automation & Scripting that a Game Design-published `script_patch_version` is available for tenant-readiness ingestion. If an empty affected-script list reaches the receiver, it returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` before readiness mutation or synthetic handler work; this defensive rejection is not a readiness terminal result. ADR 0115's required durable `FAILED` record with status/audit evidence remains unimplemented. - Event-ingress RPCs such as `TriggerScriptEvent` or a batch equivalent deliver script events from domain services and must carry runtime scope, idempotency, and patch-selection fields as described below. - `GetDraftDesignDigest` – accepts a typed scope selector `oneof { versionId, scriptPatchVersion }`; the current registered receiver returns `UNSUPPORTED_SCOPE` for both scopes rather than exposing helper results that lack exact publication mapping. diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 641d782a86..c4125b0454 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -21,7 +21,7 @@ The plugin lifecycle histories are separate ADR 0163 retained families. `plugin_ The current admission barrier supports the optional regional selector and now implements the durable acknowledgement slice: boundary normalization preserves exact scope/mode/request identity, a length-delimited SHA-256 fingerprint binds the request, and immutable `APPLIED`/`ALREADY_APPLIED` history supports exact retry readback and changed-input conflict. The operator Get path performs a read-only exact-scope lookup, returns `NOT_FOUND` for an absent state and `ACKNOWLEDGEMENT_UNAVAILABLE` when durable successful history is missing, and never reconstructs missing history from mutable state. Response fields expose the successful acknowledgement identity, target mode, fingerprint, outcome, and timestamp. Direct V1 schema and focused unit proof cover this slice. Exact-head hosted CI, Automation service checks, and generic full-stack smoke passed. Hosted `integrationTest` executed against Docker/PostgreSQL and passed, but the hosted logs/artifact do not expose a trustworthy exact test count; the local exact-head integration run discovered 33 tests and skipped all 33 because Docker/Testcontainers was unavailable. Generic full-stack smoke did not exercise admission behavior and is not claimed as admission proof. The separate preview endpoint was unavailable at capacity. The target owner contract is [SetAutomationAdmissionMode](../../system-architecture-scripting-control-plane-api.md#setautomationadmissionmode); the [local API contract](./api-contracts.md#script-patch-and-plugin-visibility-apis) records this service's consequence. Immutable admission request history currently has no cleanup and remains retained; safe pruning and production launch require a future ADR 0163/ADR 0123 owner, horizon, and tombstone design, so this boundary adds no arbitrary TTL. -Tenant-readiness mutation now serializes per tenant, preserves admitted identities on retry, and fails duplicate or unresolved script names before admission. The V2 unique active-tenant index fails closed on retained duplicates. The RPC reports the readiness owner's boolean result rather than unconditional success. An empty `affectedScripts` notification returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` and admits no synthetic work, but it still creates no readiness row. ADR 0115 requires a durable `FAILED` status with normal audit evidence for an identifiable patch without verified zero-handler proof; the current projection owner does not yet provide that terminal-write operation. PostgreSQL proof and the remaining manifest, notification, generation-fence, and recovery gaps are recorded in the [Automation implementation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#current-status); this bounded correction is not complete publication readiness. +Tenant-readiness mutation now serializes per tenant, preserves admitted identities on retry, and fails duplicate or unresolved script names before admission. The V2 unique active-tenant index fails closed on retained duplicates. The RPC reports the readiness owner's boolean result rather than unconditional success. If an empty notification reaches Automation, the command service returns `false` before readiness mutation or Temporal tracking, and the RPC returns `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; this defensive response does not mark a patch `READY`. The durable `FAILED` status with normal audit evidence required by ADR 0115 for an identifiable patch without verified zero-handler proof remains unavailable from the current projection owner. PostgreSQL proof and the remaining manifest, notification, generation-fence, and recovery gaps are recorded in the [Automation implementation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#current-status); this bounded correction is not complete publication readiness. The same V2 migration replaces handler work-item and audit identities so authenticated `sourceService` participates in both pinned and unpinned uniqueness. Ingress now supplies that owner-derived value to repository duplicate checks, conflict targets, and exact readback, so equal producer-local event identities from different services remain independent while an exact same-source retry deduplicates. Migration-shape and focused repository tests execute locally; the PostgreSQL same-source/different-source integration case compiles but was skipped because Docker was unavailable. This does not close the separate namespace, sealed-manifest, lifecycle-fence, replay, or retention gaps. @@ -78,7 +78,7 @@ Publication consumes this empty-only receipt only within the [canonical selected - AI computations are optimized for large worlds by evaluating scripts on a separate schedule and batching the resulting commands before handing them to the tick system. - Script definitions are versioned and can be hot reloaded without downtime as described in [System Architecture: Scripting & Automation](../../system-architecture-scripting.md). Detailed sandbox and loop-safety rules live in [Script Sandbox & Resource Limits](./sandbox-runtime-design.md). - For a non-empty `NotifyScriptVersionUpdate` notification, the service reloads the specified patch into tenant-readiness state, validating compatibility and running `onLoad` before any running instance is allowed to switch to it. Tenant readiness is single-pending per tenant: if a newer publish arrives before the current pending patch reaches a terminal state, the older pending patch becomes `SUPERSEDED` and cannot later advance to `READY`. -- In the current normal Game Design integration, `affectedScripts` is empty. The receiver returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; no readiness row or synthetic handler work is created, and Temporal tracking is not started. This is fail-closed containment, not the accepted terminal outcome: for an identifiable tenant/patch without verifiable zero-handler proof, ADR 0115 requires one durable `FAILED` readiness record with normal status/audit evidence. The current readiness owner lacks an operation for that terminal write, so the required record remains a publication blocker. An unidentifiable malformed notification may fail validation without fabricating a readiness identity. +- New Game Design patch-publication attempts without an owner-verified affected-handler manifest fail with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification; pre-existing `PENDING` attempts may already have dispatched and require owner reconciliation, not redispatch. See [Game Design Version Control](../game-design-service/version-control.md#script-patch-versions-and-runtime-behavior) and the [patch-containment tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). - **Target state:** Runtime execution is instance-aware even when patch readiness is tenant-scoped: a tenant-level `READY` patch is only eligible for pinning, while admission, timer scheduling, and scoped Automation admission pause are evaluated per ``, and plugin activation is evaluated per ``. Plugin-backed work captures the Automation-owned `pluginActivationEpoch` and owner `lifecycleRevision` and preserves and revalidates both through evaluation, persistence, handoff, staged/final effects, retry, replay, and recovery. Game Session remains the sole authority for the exact `(scriptPatchVersion, scriptPinEpoch)` execution tuple and its owner-grounded `controlPlaneRequestId` evidence; runtime surfaces carry and compare the request ID with the patch and epoch, and absent or mismatched evidence fails closed. The request ID is correlation/readback evidence, not a third pin-identity component. - Automation is also a lifecycle owner for these instance-scoped work, schedule, and plugin-runtime families: each family must be registered with World Management's durable cleanup-owner inventory, expose idempotent cleanup and acknowledgement, and retain namespace-backed durable state according to its S1/S2/S3 classification. A missing owner registration or cleanup acknowledgement blocks termination; local queue/drain state and workflow history are diagnostic only. - **Current cleanup behavior:** The scheduled `ScriptWorkItemServiceImpl.cleanupTerminalWorkItems` path selects eligible `HANDED_OFF` and `CANCELED` `script_work_items` rows under lock, applies each status-specific parent age cutoff, and requires every associated handoff event to have a completed outcome, no active hold, and an `observed_at` before that same cutoff. Within the caller transaction, it detaches nullable `script_event_audit.work_item_id` links, deletes eligible `script_handoff_events` children, and then deletes the parent rows. A newer child retains the parent bundle until its own age condition is met. Any retained `script_dead_letter_replay_results` row blocks parent deletion regardless of age; retained audit rows remain under their independent retention policy. Separately, `ScriptHandoffEventRepository.deleteExpiredRetentionEvidence` exposes a child-only sweep in ordered batches of at most 500. It deletes only completed, expired, unheld handoffs when every sibling is also eligible, no replay receipt is retained, and the existing parent is terminal but not `DEAD_LETTERED`; orphaned children with a missing parent are not eligible. It does not require the existing parent to pass a status-specific age cutoff. This repository method has no current scheduled caller. Automatic age- and row-cap cleanup of `DEAD_LETTERED` parents fails closed and deletes nothing: the live schema has a per-work-item `failure_generation` and generation-bound replay-result receipts, but it does not yet retain the recovery aggregate's generation-bound claim/attempt state, expected-child ledger, or evidence-retention horizons needed to prove whole-bundle eligibility and completed `resumed_dispatch`. Focused unit proof covers fail-closed parent cleanup and the bounded handoff query; PostgreSQL retention cases require Docker/Testcontainers at execution time. Target cleanup must retain or explicitly dispose each child handoff/audit record under its owning retention, safety-evidence, replay, and lifecycle contracts, and only delete a parent when those child dispositions and required audit evidence are durably settled. The target retention rules remain owned by the scripting normative contracts and applicable lifecycle/operations documents. @@ -122,9 +122,9 @@ Tick-driven automation and event handling never use synchronous sagas or Tempora ## Hot Reload and Failure Handling -For a non-empty `NotifyScriptVersionUpdate` notification, tenant-scoped readiness ingestion is intended for ``. Instance-scoped reload happens later only when Game Session pins an already-`READY` patch for a specific runtime scope. In the current normal Game Design integration, `affectedScripts` is empty; the handler returns before creating a readiness row and the conditional Temporal tracking hook does not run: +Tenant-scoped readiness ingestion is intended for ``. Instance-scoped reload happens later only when Game Session pins an already-`READY` patch for a specific runtime scope: -- `NotifyScriptVersionUpdate` is a tenant-readiness ingestion signal, not an instance activation signal. It causes the service to ingest compiled graphs and bindings for ``, then run tenant-scoped readiness checks and `onLoad` before any running instance is allowed to pin that patch. +- `NotifyScriptVersionUpdate` is a tenant-readiness ingestion signal, not an instance activation signal. For a non-empty notification accepted by the readiness owner, the service ingests compiled graphs and bindings for ``, then runs tenant-scoped readiness checks and `onLoad` before any running instance is allowed to pin that patch. - Tenant readiness uses the patch lifecycle `PENDING_VALIDATION -> ONLOAD_RUNNING -> READY/FAILED`, plus terminal `SUPERSEDED` when a newer publish displaces an older pending patch for the same tenant. - **Target state:** Runtime scopes track the exact patch and pin epoch observed from Game Session for `` plus the owner-committed `controlPlaneRequestId` that produced that observation, alongside instance-scoped admission state such as `reloadState` and a scoped Automation admission pause. The Automation projection persists and retains that request ID through reload/convergence and relevant handoff/recovery evidence, exposing it as `lastObservedControlPlaneRequestId`; it remains projection evidence, not pin or rollout-history authority. A notification or stale/gapped projection starts a bounded owner reread; it does not advance the projection or authorize reload by arrival order, and lower, reordered, or contradictory producer tuples/cursors are rejected. - **Target state:** When Game Session later commits a tenant-`READY` patch for a specific runtime scope, leaders set runtime-scope `pendingPatchVersion`/`pendingPinEpoch` and the committed pin-mutation `controlPlaneRequestId`, with `reloadState=RELOADING` while retaining the captured tuple and request identity of already-admitted work. New script/plugin triggers pause for that scope; ordinary Game Session gameplay ticks continue. In-flight evaluation may finish computation against its immutable captured graph, but every persistence, handoff, and final gameplay boundary enforces the captured patch and epoch plus any captured plugin activation epoch/lifecycle revision; reload/convergence and recovery evidence retain the owner request ID rather than a locally invented correlation. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 1ab3681ed2..61961cc505 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -123,7 +123,7 @@ Queued player commands persist `targetEntityId`, `regionId`, `regionEpoch`, and Matched handlers materialize durable `script_work_items` with event, handler, source, plugin, routing, scope, quota, and admission provenance. Ordinary work can be claimed through the explicit `PENDING_EVALUATION` to `EVALUATING` transition, evaluated from persisted script definitions, canceled durably for patch/plugin rollback or drain, and dead-lettered/replayed under compatibility gates. Tenant-readiness `onLoad` follows readiness-owner terminalization and generic dead-letter replay rejects it with `onload_not_replayable`; stale readiness work remains unreclaimed. Handler-scoped `script_event_audit` rows remain distinct from ingress audit and record cancellation and terminal outcomes. -Current status: `VersionServiceImpl.publishScriptPatchVersion` in Game Design still sends an empty `affectedScripts` list. The Automation receiver now returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; no readiness row, synthetic handler work, or Temporal readiness workflow is created. The empty request is safely rejected, but this does not satisfy ADR 0115: an identifiable patch without verified zero-handler proof requires one durable `FAILED` readiness record with normal status/audit evidence. The existing `ScriptPatchReadinessProjectionService` has no failed-terminal operation for a missing/unverifiable manifest, while `beginPatchReadiness` interprets an empty script set as `READY`; therefore that operation cannot be safely composed from the current owner API. Adding it requires extending the readiness projection owner/repository and focused durable status/audit proof, outside this receiver-only slice. Non-empty notifications now propagate the returned readiness-admission boolean instead of unconditionally reporting success; accepted readiness still is not `READY`. The immutable expected-handler manifest, source publication sequence/base binding, notification failure recovery, and readiness recovery gaps remain. Target ownership and the expected-handler/terminal-outcome contract are canonical in [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). +Current status: Newly reserved Game Design patch-publication attempts without an owner-verified handler manifest fail with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification; failure retains the canonical DRAFT/tuple reservation, exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing `PENDING` attempts may already have dispatched and require owner reconciliation, not redispatch; historical `SUCCEEDED` replay does not notify again. See [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). The Automation client surfaces rejected notification responses. If an empty notification reaches Automation, its receiver returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` before readiness mutation or Temporal tracking; this defensive rejection is not positive readiness. It does not satisfy [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md): an identifiable patch without verified zero-handler proof requires a durable `FAILED` readiness record with normal status/audit evidence, but the current `ScriptPatchReadinessProjectionService` has no failed-terminal operation. `beginPatchReadiness` interprets an empty script set as `READY`, so it cannot safely stand in for that failure operation. The immutable expected-handler manifest, source publication sequence/base binding, notification failure recovery, and readiness recovery gaps remain. Non-empty notifications still propagate the readiness-admission boolean; accepted readiness is not `READY`. The registered `GetDraftDesignDigest` receiver now returns `UNSUPPORTED_SCOPE` for both full-version and script-patch requests after exact caller/request-binding validation. The existing full digest is tenant-wide and uses a synthetic commit marker; the helper patch digest does not establish the required owner-verified base-bound publication manifest. The separate selected-empty full-version reader remains unregistered. Exact version mapping and patch-manifest attestation remain blockers before either scope can return a publication digest. The readiness refresh path still needs explicit recovery for activity retry exhaustion so an `ONLOAD_RUNNING` projection cannot remain stranded; mixed live/dry-run proof must also ensure dry-run `onLoad` work cannot advance the live readiness projection. These remain target implementation and proof gaps. From d476f7fe20b24751a0466605d13b3645defa0723 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:10:25 +1300 Subject: [PATCH 09/11] Log retained script patch publication failures with workflow context --- .../firemud/gamedesign/service/impl/VersionServiceImpl.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 8c9df9b9c0..0cc809feac 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -215,6 +215,12 @@ public VersionDto publishScriptPatchVersion( retryableParticipantDependencyFailure ? retryableParticipantDependencyFailureMessage() : publishFailureMessage(operationFailure); + logger.warn( + "Script patch publish failed for tenant {} workflow {} with code {}", + tenantId, + publishWorkflowId, + failureCode, + operationFailure); ScriptPatchFinalization failure; try { failure = From d253e1e33c5ab1bf481c26bb618dc90a6e71f608 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:27:34 +1300 Subject: [PATCH 10/11] Align patch publication proof and Entity replay fixtures with guarded paths --- .../api-contracts.md | 2 +- .../game-design-service/api-contracts.md | 2 +- .../game-design-service/version-control.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../impl/EntityManagementGrpcServiceTest.java | 37 ++++++++++++++----- 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 6a821307e7..735bf805dc 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -25,7 +25,7 @@ Target formation control-plane behavior eliminates unauthenticated service-local - `GetScriptBreakerStatus` and `ListScriptBreakerEvents` are target-state reads for the exact `(tenantId, gameInstanceId, scriptPatchVersion, scriptPinEpoch, scriptId)` core-script breaker identity, and `ResetScriptBreaker` is its target operator mutation. The current proto/implementation has no authoritative breaker status/history surface, monotonic breaker revision, reset mutation, stored request result, or reset evidence. They are distinct from `GetScriptPatchStatus` tenant readiness and `GetScriptStatus` pre-DSL work states; do not introduce or infer a `scriptVersionId`. - Target pre-DSL recovery permits rebuilding `PENDING_EVALUATION` and only an `EVALUATING` row whose owner proves the lease stale or explicitly releases ownership through one fenced compare-and-set covering the status, owner, freshness, and fence transition; unresolved, ambiguous, and non-stale rows remain excluded. The callable `rebuildPendingWorkItemIndex` remains an unsafe helper with no stale, owner, or compare-and-set reconciliation gate, so current queue reset/resume is unavailable and must fail closed; no live scheduled rebuild invokes it, and a non-atomic status preflight cannot authorize recovery. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). It does not implement target `PENDING`/`INDEXED` evaluated-descriptor rebuild because the separate descriptor status layer is not currently persisted; these pointers are not evaluated-command queue entries or descriptor replay evidence. - For a non-empty `NotifyScriptVersionUpdate` notification, the current path validates and stages patches through `PENDING_VALIDATION -> ONLOAD_RUNNING -> READY/FAILED/SUPERSEDED`; running instances reload only after a later pin change to that tenant-`READY` patch. -- New Game Design patch-publication attempts without an owner-verified affected-handler manifest fail with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification; a pre-existing `PENDING` attempt may already have dispatched and requires owner reconciliation, not redispatch. See [Game Design Version Control](../game-design-service/version-control.md#script-patch-versions-and-runtime-behavior) and the [patch-containment tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). If an empty `NotifyScriptVersionUpdate` request reaches this receiver, it returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; this defensive response is not positive readiness. For an identifiable patch without verifiable zero-handler proof, the durable `FAILED` status/audit required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) remains unimplemented. An unidentifiable malformed notification may fail validation without fabricating a patch identity. For non-empty notifications, the readiness boolean is propagated to the RPC response; `success=true` means the owner accepted the current readiness operation, not that all handlers reached `READY`. +- New Game Design patch-publication attempts cannot reach notification without an owner-verified affected-handler manifest. With controlled participant results that pass the gate, absence fails with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE`; this registered receiver instead returns `UNSUPPORTED_SCOPE` for its digest read, which Game Design surfaces as `PARTICIPANT_UNAVAILABLE` before the manifest check. A pre-existing `PENDING` attempt may already have dispatched and requires owner reconciliation, not redispatch. See [Game Design Version Control](../game-design-service/version-control.md#script-patch-versions-and-runtime-behavior) and the [patch-containment tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). If an empty `NotifyScriptVersionUpdate` request reaches this receiver, it returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable`; this defensive response is not positive readiness. For an identifiable patch without verifiable zero-handler proof, the durable `FAILED` status/audit required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) remains unimplemented. An unidentifiable malformed notification may fail validation without fabricating a patch identity. For non-empty notifications, the readiness boolean is propagated to the RPC response; `success=true` means the owner accepted the current readiness operation, not that all handlers reached `READY`. - The current `ListScriptHandoffEvents` proto/client reads handoff rows using `workItemId`/persisted `outboxWorkItemId`, `gameSessionCommandId`, `automationDispatchId`, and the currently supported scope, remote, provenance, routing, target, and source fields. The target complete Command-Handoff Identity and complete evaluated-descriptor semantics remain target-only end-to-end; locally stored ordinal/text/target values do not establish that target contract. The current proto/client exposes no `bindingId` request filter, and target response metadata remains target-state follow-through rather than a claimed live field. - `GetAutomationPinConvergence` is currently served from a durable Automation-owned `script_patch_pin_projections` view keyed by `(tenantId, gameInstanceId)` and returns freshness flags (`projectionAsOfMs`, `projectionLagMs`, `isProjectionStale`) so temporary Game Session read failures do not collapse operator visibility into raw pass-through coupling. - Signer/component-policy enforcement is live on the Automation runtime side. The current control-plane surface exposes `GetPluginStatus`, `ListPluginRuntimeEvents`, and `GetPluginPolicyConvergence`, and scheduled reconciliation disables enabled plugins when current publication metadata becomes fail-closed. The separate propagation-event families `SignerPolicyVersionObserved` and `SignerRevocationApplied` remain target-state follow-through rather than a shipped API family. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5964deb9c4..517972c96b 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -102,7 +102,7 @@ The following implementation and proof gaps remain in these live paths: - `PublishedReleaseBundle` retains `tenantId` in the entity/DTO but the current proto has no tenant field and the gRPC mapper does not emit it. Consumers cannot exact-compare the requested `(tenantId, versionId)` against the returned attestation; the target deterministic tenant/version response and fail-closed consumer comparison remain unimplemented. - `UploadPluginBundle` parses and verifies bytes before it creates a durable publication row or status event. Parse, malformed-manifest, archive-limit, and signature failures therefore cannot produce the target `UPLOAD_REJECTED` row/event, and the request has no stable retry identity or pre-parse raw-upload digest. The target intake boundary must durably record an attempt/rejection before or alongside parsing and compute `rawUploadDigest` as `sha256:<64 lowercase hexadecimal characters>` (SHA-256 over the exact received bytes, with no archive normalization, decompression, or transport metadata) under positive `rawUploadDigestSchemaVersion=1` before archive parsing; the normalized request binds that digest and schema version to the tenant and stable request identity. This raw-upload digest is distinct from the post-parse `bundleDigest` over canonical extracted entries. An identifiable plugin version may receive `UPLOAD_REJECTED`, while malformed or unidentifiable input must remain a tenant/request-scoped durable rejection without inventing plugin identity; exact retries replay only when the complete binding, including the raw-upload digest and schema version, matches, and changed request digests conflict. Focused proof for both identifiable and unidentifiable rejection is absent. -Script-patch publication is contained by the [manifest, retained-attempt and launch-evidence contract](version-control.md#script-patch-versions-and-runtime-behavior). New attempts cannot publish without an owner-verified handler manifest and return typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification, retaining the canonical Draft tuple and terminal failure. Prior PENDING attempts remain for reconciliation; historical success replay does not redispatch. The Automation client surfaces response rejection and preserves identifiable empty-handler dispatch to the readiness owner. Source-bound descriptor creation, retained replay and exact readback refuse nonblank patches without exact published-for-base and Automation `READY` evidence. `GetPublishedScriptPatchVersion` still requires the complete `(tenantId, baseVersionId, scriptPatchVersion)` tuple and exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. These guards do not implement a manifest producer, complete base-version authorization, readiness convergence, or player activation. Current proof limits belong to [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). +Script-patch publication is contained by the [manifest, retained-attempt and launch-evidence contract](version-control.md#script-patch-versions-and-runtime-behavior). New attempts cannot publish without an owner-verified handler manifest. After participant gates pass, absence returns typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification, retaining the canonical Draft tuple and terminal failure. The current registered Automation digest receiver returns `UNSUPPORTED_SCOPE`, surfaced as `PARTICIPANT_UNAVAILABLE` before the manifest check; controlled passing participant results qualify the later manifest-refusal branch. Prior PENDING attempts remain for reconciliation; historical success replay does not redispatch. The Automation client surfaces response rejection and preserves identifiable empty-handler dispatch to the readiness owner. Source-bound descriptor creation, retained replay and exact readback refuse nonblank patches without exact published-for-base and Automation `READY` evidence. `GetPublishedScriptPatchVersion` still requires the complete `(tenantId, baseVersionId, scriptPatchVersion)` tuple and exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. These guards do not implement a manifest producer, complete base-version authorization, readiness convergence, or player activation. Current proof limits belong to [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). The target tenant-scoped `GetTemplateReferencePhase` RPC is not implemented: it has no current proto RPC or registered handler. Prepared owner-local reference-phase storage and reads remain unregistered and confer no live launch or retirement authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 3636ed91c0..3a22b5c8e1 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -314,7 +314,7 @@ opaque JSON blobs or service-specific payloads. Script-only fixes are tracked as `scriptPatchVersion` values attached to a `baseVersionId`. Together, `(baseVersionId, scriptPatchVersion)` identify the effective published script artifact and its base-cohesion/cache context for a game. A script-only publication may also receive a separate `versionId` for publication metadata and history; that identifier does not replace the base-version/patch pair when resolving the effective script artifact. The Game Design owner now rejects a new publish request when any retained script-only row already owns the same tenant/base/patch tuple, and V27 fails closed on retained incomplete or duplicate tuples before installing the matching partial unique index; it does not choose or delete a retained winner. A same-request retry continues through its durable publish-attempt outcome before that tuple-conflict check. For a V25 legacy script-patch quarantine that leaves a `FAILED` attempt and candidate after the original `PENDING` request digest could not be recovered, the original request cannot safely be replayed because the attempt cannot establish same-request identity without its stable digest. Publish any replacement with a new `scriptPatchVersion` and retain the quarantined candidate and attempt; the retained candidate continues to reserve its tenant/base/patch tuple. Dispose of an abandoned candidate only after the Game Design data owner proves it is an abandoned `DRAFT` under the [V27 migration preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight), including that no release bundle, active/launch/remap dependency, dependent publish attempt, or artifact workflow still requires it. That proof must account for the retained attempt and its dependencies; removal is an owner-approved disposition, not automatic quarantine cleanup. Exact publication metadata lookup requires one script-only row for the tenant/base/patch tuple in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state; new Game Session pin admission remains independently `PUBLISHED`-only. The accepted Game Session runtime execution pin and rollback fence remain the exact `{scriptPatchVersion, scriptPinEpoch}` tuple; `baseVersionId` is separately validated as the patch's base-cohesion and artifact context and does not silently add a field to Trigger Identity or replace that pin tuple. Artifact, cache, and runtime-read contracts that resolve an effective script artifact must carry and exact-compare the base-version/patch pair; the tenant readiness lifecycle and its readiness identity remain keyed by `scriptPatchVersion` as defined by Automation & Scripting's canonical lifecycle. -Script-patch publication must prove the immutable owner-verified affected-script/handler manifest before notification or publication success. An absent manifest fails with bounded `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before dispatch. A newly reserved attempt may record that failure while retaining its canonical Draft candidate and tuple; exact replay reads its terminal outcome. A pre-existing PENDING attempt is potentially dispatched evidence and requires reconciliation rather than redispatch or cleanup inferred from manifest absence. Historical SUCCEEDED replay does not send another notification. Identifiable empty-handler notifications remain dispatchable to the Automation readiness owner for the durable outcome required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md); transport acceptance never substitutes for manifest or `READY` proof. +Script-patch publication must prove the immutable owner-verified affected-script/handler manifest before notification or publication success. After participant gates pass, an absent manifest fails with bounded `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before dispatch. Current manifest-refusal proof uses controlled passing participant results: the registered Automation digest receiver returns `UNSUPPORTED_SCOPE`, surfaced by the gate as `PARTICIPANT_UNAVAILABLE` before that check. A newly reserved attempt may record that failure while retaining its canonical Draft candidate and tuple; exact replay reads its terminal outcome. A pre-existing PENDING attempt is potentially dispatched evidence and requires reconciliation rather than redispatch or cleanup inferred from manifest absence. Historical SUCCEEDED replay does not send another notification. Identifiable empty-handler notifications remain dispatchable to the Automation readiness owner for the durable outcome required by [ADR 0115](../../decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md); transport acceptance never substitutes for manifest or `READY` proof. Launch selection, retained descriptor replay and exact descriptor readback require exact published-for-base patch identity and canonical Automation `READY` evidence. Without that evidence, a nonblank patch fails with `SCRIPT_PATCH_NOT_READY`; a retained digest alone cannot authorize its use. Unpatched descriptors retain their existing source, immutable request/result and release checks. Current source and unrun proof status are recorded in [the implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#script-patch-publication-containment). 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 d59caf5070..93162a116b 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 @@ -423,7 +423,7 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Script Patch Publication Containment -The local receiving preparation preserves the stronger public full-publication authorization refusal and selected-full schema-4 operation/capture and release contracts. The old synchronous-fallback donor change is superseded by that denial. For patch publication, new reserved attempts pass the available participant gates but fail with typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification because no owner-verified handler manifest is available. Failure retains the current canonical DRAFT/tuple reservation; exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing PENDING originals remain potentially dispatched evidence needing reconciliation. Historical success replay performs no new notification. The Automation client surfaces rejected responses while allowing identifiable empty-handler notifications to reach the readiness owner governed by ADR 0115. +The local receiving preparation preserves the stronger public full-publication authorization refusal and selected-full schema-4 operation/capture and release contracts. The old synchronous-fallback donor change is superseded by that denial. For patch publication with controlled participant results that pass the gate, new reserved attempts fail with typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification because no owner-verified handler manifest is available. The current registered Automation digest receiver instead returns `UNSUPPORTED_SCOPE`, which the participant gate surfaces as `PARTICIPANT_UNAVAILABLE` before the manifest check; the focused manifest-refusal proof does not establish a production path past that earlier refusal. Failure retains the current canonical DRAFT/tuple reservation; exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing PENDING originals remain potentially dispatched evidence needing reconciliation. Historical success replay performs no new notification. The Automation client surfaces rejected responses while allowing identifiable empty-handler notifications to reach the readiness owner governed by ADR 0115. New patched launch selection already fails closed. The receiving correction additionally refuses a retained patched descriptor after exact immutable request/source/result verification, for both replay and readback; it preserves valid unpatched resolution. No manifest, readiness receipt, digest, pin epoch or cleanup/release protocol is invented. Canonical semantics remain in [Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index b6fa3f706a..46d37fbe00 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -81,6 +81,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; import tools.jackson.databind.ObjectMapper; class EntityManagementGrpcServiceTest { @@ -313,12 +315,19 @@ private EntityMutationEffectReplayService effectReplayService() { Mockito.when( service.execute( Mockito.anyLong(), - Mockito.anyString(), + Mockito.nullable(String.class), Mockito.anyString(), Mockito.any(), Mockito.any())) .thenAnswer( - invocation -> ((java.util.function.Supplier) invocation.getArgument(3)).get()); + invocation -> { + String effectId = invocation.getArgument(1); + if (effectId == null || effectId.isBlank()) { + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, "Effect id is required for replay-guarded mutations"); + } + return ((java.util.function.Supplier) invocation.getArgument(3)).get(); + }); return service; } @@ -1061,7 +1070,7 @@ void putItemIntoContainerReturnsMappedItem() { null, null, 2, - null, + "effect-put-1", "41")) .thenReturn( new net.firedevops.firemud.entitymanagement.dto.ContainerContentEntryDto( @@ -1088,6 +1097,7 @@ void putItemIntoContainerReturnsMappedItem() { .PLAYABLE_STATE_SCOPE_SHARED) .setItemId("11") .setQuantity(2) + .setEffectId("effect-put-1") .build(), new StreamObserver<>() { @Override @@ -1135,7 +1145,7 @@ void putItemIntoContainerPassesExplicitItemInstanceId() { 44L, null, 1, - null, + "effect-put-2", "41")) .thenReturn( new net.firedevops.firemud.entitymanagement.dto.ContainerContentEntryDto( @@ -1163,6 +1173,7 @@ void putItemIntoContainerPassesExplicitItemInstanceId() { .setItemId("11") .setQuantity(1) .setItemInstanceId("44") + .setEffectId("effect-put-2") .build(), new StreamObserver<>() { @Override @@ -1336,7 +1347,7 @@ void takeItemFromContainerReturnsMappedInventoryItem() { null, null, 1, - null, + "effect-take-1", "41")) .thenReturn( new net.firedevops.firemud.entitymanagement.dto.InventoryEntryDto( @@ -1363,6 +1374,7 @@ void takeItemFromContainerReturnsMappedInventoryItem() { .PLAYABLE_STATE_SCOPE_SHARED) .setItemId("11") .setQuantity(1) + .setEffectId("effect-take-1") .build(), new StreamObserver<>() { @Override @@ -1407,7 +1419,7 @@ void takeItemFromContainerPassesExplicitItemInstanceId() { 44L, null, 1, - null, + "effect-take-2", "41")) .thenReturn( new net.firedevops.firemud.entitymanagement.dto.InventoryEntryDto( @@ -1435,6 +1447,7 @@ void takeItemFromContainerPassesExplicitItemInstanceId() { .setItemId("11") .setItemInstanceId("44") .setQuantity(1) + .setEffectId("effect-take-2") .build(), new StreamObserver<>() { @Override @@ -3448,7 +3461,7 @@ void wearEquipmentReturnsEquippedItem() { .PLAYABLE_STATE_SCOPE_SHARED, 99L, null, - null, + "effect-wear-1", "41")) .thenReturn(dto); io.micrometer.core.instrument.MeterRegistry meterRegistry = @@ -3477,6 +3490,7 @@ void wearEquipmentReturnsEquippedItem() { net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED) .setItemId("99") + .setEffectId("effect-wear-1") .build(), new StreamObserver<>() { @Override @@ -3619,7 +3633,7 @@ void removeEquipmentReturnsRemovedItem() { net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED, "HEAD", - null, + "effect-remove-1", "41")) .thenReturn(dto); io.micrometer.core.instrument.MeterRegistry meterRegistry = @@ -3648,6 +3662,7 @@ void removeEquipmentReturnsRemovedItem() { net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED) .setSlot("HEAD") + .setEffectId("effect-remove-1") .build(), new StreamObserver<>() { @Override @@ -3746,7 +3761,7 @@ void pickupItemFromRoomReturnsInventoryItem() { null, null, 1, - null, + "effect-pickup-1", "41")) .thenReturn(dto); io.micrometer.core.instrument.MeterRegistry meterRegistry = @@ -3777,6 +3792,7 @@ void pickupItemFromRoomReturnsInventoryItem() { .setRoomInstanceId("R-1") .setItemId("99") .setQuantity(1) + .setEffectId("effect-pickup-1") .setSessionAttestation("attestation") .build(), new StreamObserver<>() { @@ -3818,7 +3834,7 @@ void dropItemToRoomReturnsRoomGroundItem() { null, null, 1, - null, + "effect-drop-1", "41")) .thenReturn(dto); io.micrometer.core.instrument.MeterRegistry meterRegistry = @@ -3849,6 +3865,7 @@ void dropItemToRoomReturnsRoomGroundItem() { .setRoomInstanceId("R-1") .setItemId("99") .setQuantity(1) + .setEffectId("effect-drop-1") .setSessionAttestation("attestation") .build(), new StreamObserver<>() { From a2f7c62d82ba3018f516503ba7f295a96b4db04c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:30:17 +1300 Subject: [PATCH 11/11] Align retained publication failure and containment proof --- ...ystem-architecture-authz-route-matrix.yaml | 6 ++-- .../automation-and-scheduler-runtime.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../service/impl/VersionServiceImpl.java | 12 +++---- .../service/impl/VersionServiceImplTest.java | 16 ++++----- .../WorldLifecycleCommandServiceImplTest.java | 36 +++++++++---------- 6 files changed, 36 insertions(+), 38 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 5346b77e49..93293d9b42 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -886,8 +886,8 @@ routes: roles: any_of: [designer, tenantAdmin] implementation_status: + current_behavior: legacy_adapter_returns_501_crafting_unavailable_before_parsing_or_service_dispatch known_drift: - - route_omitted_from_current_authoritative_openapi_and_controller_accepts_caller_tenant_id - recipe_lookup_and_update_are_not_tenant_qualified - cross_tenant_result_and_ingredient_item_ownership_is_not_proved - service: entity-management-service @@ -913,9 +913,9 @@ routes: roles: any_of: [designer, tenantAdmin] implementation_status: + current_behavior: legacy_adapter_returns_501_crafting_unavailable_before_parsing_or_service_dispatch known_drift: - - route_omitted_from_current_authoritative_openapi_and_recipe_id_lookup_is_global_shaped - - cross_tenant_recipe_and_item_read_is_not_proved_denied + - underlying_service_recipe_and_item_read_remains_unsafe_for_exposure_without_tenant_authorization - service: automation-scripting-service route: POST /formations scope: tenant diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 61961cc505..f2b9a4b77f 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -123,7 +123,7 @@ Queued player commands persist `targetEntityId`, `regionId`, `regionEpoch`, and Matched handlers materialize durable `script_work_items` with event, handler, source, plugin, routing, scope, quota, and admission provenance. Ordinary work can be claimed through the explicit `PENDING_EVALUATION` to `EVALUATING` transition, evaluated from persisted script definitions, canceled durably for patch/plugin rollback or drain, and dead-lettered/replayed under compatibility gates. Tenant-readiness `onLoad` follows readiness-owner terminalization and generic dead-letter replay rejects it with `onload_not_replayable`; stale readiness work remains unreclaimed. Handler-scoped `script_event_audit` rows remain distinct from ingress audit and record cancellation and terminal outcomes. -Current status: Newly reserved Game Design patch-publication attempts without an owner-verified handler manifest fail with `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification; failure retains the canonical DRAFT/tuple reservation, exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing `PENDING` attempts may already have dispatched and require owner reconciliation, not redispatch; historical `SUCCEEDED` replay does not notify again. See [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). The Automation client surfaces rejected notification responses. If an empty notification reaches Automation, its receiver returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` before readiness mutation or Temporal tracking; this defensive rejection is not positive readiness. It does not satisfy [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md): an identifiable patch without verified zero-handler proof requires a durable `FAILED` readiness record with normal status/audit evidence, but the current `ScriptPatchReadinessProjectionService` has no failed-terminal operation. `beginPatchReadiness` interprets an empty script set as `READY`, so it cannot safely stand in for that failure operation. The immutable expected-handler manifest, source publication sequence/base binding, notification failure recovery, and readiness recovery gaps remain. Non-empty notifications still propagate the readiness-admission boolean; accepted readiness is not `READY`. +Current status: Game Design patch containment has focused proof with controlled participant results; the registered Automation digest path remains unavailable, and production manifest/readiness authority is unproved. Publication outcomes, retained-attempt custody and replay are defined by the [canonical Version Control contract](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). The Automation client surfaces rejected notification responses. If an empty notification reaches Automation, its receiver returns `success=false` with `FAILED_PRECONDITION / zero_handler_manifest_unverifiable` before readiness mutation or Temporal tracking; this defensive rejection is not positive readiness. It does not satisfy [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md): an identifiable patch without verified zero-handler proof requires a durable `FAILED` readiness record with normal status/audit evidence, but the current `ScriptPatchReadinessProjectionService` has no failed-terminal operation. `beginPatchReadiness` interprets an empty script set as `READY`, so it cannot safely stand in for that failure operation. The immutable expected-handler manifest, source publication sequence/base binding, notification failure recovery, and readiness recovery gaps remain. Non-empty notifications still propagate the readiness-admission boolean; accepted readiness is not `READY`. The registered `GetDraftDesignDigest` receiver now returns `UNSUPPORTED_SCOPE` for both full-version and script-patch requests after exact caller/request-binding validation. The existing full digest is tenant-wide and uses a synthetic commit marker; the helper patch digest does not establish the required owner-verified base-bound publication manifest. The separate selected-empty full-version reader remains unregistered. Exact version mapping and patch-manifest attestation remain blockers before either scope can return a publication digest. The readiness refresh path still needs explicit recovery for activity retry exhaustion so an `ONLOAD_RUNNING` projection cannot remain stranded; mixed live/dry-run proof must also ensure dry-run `onLoad` work cannot advance the live readiness projection. These remain target implementation and proof gaps. 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 93162a116b..c82171b684 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 @@ -423,7 +423,7 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Script Patch Publication Containment -The local receiving preparation preserves the stronger public full-publication authorization refusal and selected-full schema-4 operation/capture and release contracts. The old synchronous-fallback donor change is superseded by that denial. For patch publication with controlled participant results that pass the gate, new reserved attempts fail with typed `SCRIPT_PATCH_MANIFEST_UNAVAILABLE` before notification because no owner-verified handler manifest is available. The current registered Automation digest receiver instead returns `UNSUPPORTED_SCOPE`, which the participant gate surfaces as `PARTICIPANT_UNAVAILABLE` before the manifest check; the focused manifest-refusal proof does not establish a production path past that earlier refusal. Failure retains the current canonical DRAFT/tuple reservation; exact retries replay terminal failure, and a different request cannot reuse that tuple. Pre-existing PENDING originals remain potentially dispatched evidence needing reconciliation. Historical success replay performs no new notification. The Automation client surfaces rejected responses while allowing identifiable empty-handler notifications to reach the readiness owner governed by ADR 0115. +The receiving implementation preserves public full-publication refusal and the controlled selected-full schema-4 operation/capture and release contracts. The old synchronous-fallback donor change is superseded. Patch containment has focused proof with controlled participant results; the registered Automation digest path remains unavailable, and production manifest/readiness authority is unproved. Publication outcomes, retained-attempt custody and replay are defined by the [canonical Version Control contract](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). New patched launch selection already fails closed. The receiving correction additionally refuses a retained patched descriptor after exact immutable request/source/result verification, for both replay and readback; it preserves valid unpatched resolution. No manifest, readiness receipt, digest, pin epoch or cleanup/release protocol is invented. Canonical semantics remain in [Version Control](../../architecture/microservices/game-design-service/version-control.md#script-patch-versions-and-runtime-behavior). diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 0cc809feac..3080772d3a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -63,8 +63,8 @@ public class VersionServiceImpl implements VersionService { private static final int DEFAULT_PLUGIN_VERSION_STATUS_LIMIT = 100; private static final int MAX_PLUGIN_VERSION_STATUS_LIMIT = 200; - private static final String RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE = - "PARTICIPANT_DEPENDENCY_UNAVAILABLE_RETRYABLE"; + private static final String PARTICIPANT_DEPENDENCY_FAILURE_CODE = + "PARTICIPANT_DEPENDENCY_UNAVAILABLE"; private static final Logger logger = LoggingUtil.getLogger(VersionServiceImpl.class); @@ -209,11 +209,11 @@ public VersionDto publishScriptPatchVersion( // This newly reserved path never dispatches readiness, even after the participant gate. String failureCode = retryableParticipantDependencyFailure - ? RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + ? PARTICIPANT_DEPENDENCY_FAILURE_CODE : publishFailureCode(operationFailure); String failureMessage = retryableParticipantDependencyFailure - ? retryableParticipantDependencyFailureMessage() + ? participantDependencyFailureMessage() : publishFailureMessage(operationFailure); logger.warn( "Script patch publish failed for tenant {} workflow {} with code {}", @@ -844,8 +844,8 @@ private String publishFailureMessage(RuntimeException ex) { return ex.getMessage() == null ? publishFailureCode(ex) : ex.getMessage(); } - private String retryableParticipantDependencyFailureMessage() { - return RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + private String participantDependencyFailureMessage() { + return PARTICIPANT_DEPENDENCY_FAILURE_CODE + ": participant digest gating encountered a transient dependency failure before notification; exact retries replay this failed receipt; the retained canonical patch tuple requires owner reconciliation before any new request"; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 15f28beb37..49a92deed2 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -73,8 +73,8 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; - private static final String RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE = - "PARTICIPANT_DEPENDENCY_UNAVAILABLE_RETRYABLE"; + private static final String PARTICIPANT_DEPENDENCY_FAILURE_CODE = + "PARTICIPANT_DEPENDENCY_UNAVAILABLE"; private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); @@ -759,9 +759,9 @@ void transientPreDispatchFailureRetainsCanonicalTupleAndReplaysFailure(Status.Co PublishAttempt pending = scriptPatchAttempt(binding, PublishAttemptStatus.PENDING, 11L, 8, 3L); PublishAttempt failed = scriptPatchAttempt(binding, PublishAttemptStatus.FAILED, 11L, 8, 3L); String failureMessage = - RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE + PARTICIPANT_DEPENDENCY_FAILURE_CODE + ": participant digest gating encountered a transient dependency failure before notification; exact retries replay this failed receipt; the retained canonical patch tuple requires owner reconciliation before any new request"; - failed.setFailureCode(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE); + failed.setFailureCode(PARTICIPANT_DEPENDENCY_FAILURE_CODE); failed.setFailureMessage(failureMessage); when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) .thenReturn(Optional.empty()); @@ -779,13 +779,11 @@ void transientPreDispatchFailureRetainsCanonicalTupleAndReplaysFailure(Status.Co () -> service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "notes", PUBLISH_REQUEST_ID)); - assertEquals(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); + assertEquals(PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); assertEquals(failureMessage, first.getMessage()); verify(publishAttemptService) .markScriptPatchFailed( - binding.derivedWorkflowIdentity(), - RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, - failureMessage); + binding.derivedWorkflowIdentity(), PARTICIPANT_DEPENDENCY_FAILURE_CODE, failureMessage); ScriptPatchPublishFailureException replay = assertThrows( ScriptPatchPublishFailureException.class, @@ -856,7 +854,7 @@ void transientPostGateFailureRecordsFailedReceiptAndReplaysWithoutRecollection( service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "original notes", PUBLISH_REQUEST_ID)); - assertEquals(RETRYABLE_PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); + assertEquals(PARTICIPANT_DEPENDENCY_FAILURE_CODE, first.failureCode()); assertEquals(dependencyFailure, first.getCause()); assertEquals(PublishAttemptStatus.FAILED, attempt.getStatus()); assertEquals(first.failureCode(), attempt.getFailureCode()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 9e37876dec..62b1a3b948 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -3,7 +3,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -55,6 +54,9 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionOperations; @@ -504,34 +506,32 @@ void terminatedWorldInstanceReturnsStoredSnapshotForExactRetryWithoutEffects() { regionInstanceRepository); } - @Test - void terminatedWorldInstanceRejectsDifferentOrMissingRetainedRequestIdWithoutEffects() { + @ParameterizedTest + @NullSource + @ValueSource(strings = "term-1") + void terminatedWorldInstanceRejectsDifferentOrMissingRetainedRequestIdWithoutEffects( + String retainedRequestId) { WorldInstance instance = activeWorldInstance(); instance.setStatus("TERMINATED"); - instance.setTerminationRequestId("term-1"); + instance.setTerminationRequestId(retainedRequestId); instance.setLifecycleEpoch(4L); when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) .thenReturn(Optional.of(instance)); + String requestId = retainedRequestId == null ? "term-1" : "term-2"; - IllegalArgumentException differentRequest = - assertThrows( - IllegalArgumentException.class, - () -> service.terminateWorldInstance(42L, 101L, 2L, "term-2", "stop")); - assertTrue(differentRequest.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); - assertEquals("TERMINATED", instance.getStatus()); - assertEquals(4L, instance.getLifecycleEpoch()); - assertEquals("term-1", instance.getTerminationRequestId()); + assertTerminationConflictWithoutEffects(instance, retainedRequestId, requestId); + } - instance.setTerminationRequestId(null); - IllegalArgumentException missingRetainedRequest = + private void assertTerminationConflictWithoutEffects( + WorldInstance instance, String retainedRequestId, String requestId) { + IllegalArgumentException conflict = assertThrows( IllegalArgumentException.class, - () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); - assertTrue(missingRetainedRequest.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); + () -> service.terminateWorldInstance(42L, 101L, 2L, requestId, "stop")); + assertTrue(conflict.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); assertEquals("TERMINATED", instance.getStatus()); assertEquals(4L, instance.getLifecycleEpoch()); - assertNull(instance.getTerminationRequestId()); - + assertEquals(retainedRequestId, instance.getTerminationRequestId()); verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); verifyNoInteractions( entityManagementClient,